0

I want to change an ImageView source from my code(not the xml). I have an activity and I want to change the image in it, according to a message I recieve from an other activity. Is there any method that can change the image source from the class code and not the xml code??

For example:

if (message.equals("hello")){
        //change the ImageView to hello.png;
    }
R.Jiny
  • 35
  • 1
  • 6
  • 1
    Possible duplicate of [Change Image of ImageView programmatically‎ Android](http://stackoverflow.com/questions/16906528/change-image-of-imageview-programmatically-android) – Atef Hares Feb 25 '17 at 15:12
  • 1
    you mean `ImageView.setBackgroundResource(R.drawable.hello);` where you have an image called hello.png in drawable folder ^_^ – Charuක Feb 25 '17 at 15:13
  • It sets the new image only behind the current image, I want it to change the image to the new one – R.Jiny Feb 27 '17 at 15:16

1 Answers1

0

You can do this by following the below steps:

  1. Save the images with message name(i.e. hello.png, etc).

  2. Now in your if condition use below code to set the image. Change mipmap to drawable if you have saved the images in drawable folder

    int imageId=context.getResources().getIdentifier(message,"mipmap",context.getPackageName());
    imageView.setImageResource(imageId);
    
Sanjeet
  • 2,385
  • 1
  • 13
  • 22
  • I don't understand what should I write in the message – R.Jiny Feb 27 '17 at 15:17
  • message will be your message that you are getting for ex. "hello", also using this approach you can get rid of conditional statements – Sanjeet Feb 27 '17 at 15:19
  • can you give me an exmple of how to write it? String message = ? – R.Jiny Feb 27 '17 at 15:26
  • In question you have written one `if` condition. In that there is `message.equals("hello")`. You can use the same String variable `message`. – Sanjeet Feb 27 '17 at 15:29
  • I mean what should I write when Im giving 'message' a value? – R.Jiny Feb 27 '17 at 18:26
  • That's depends on you how you are initialize that. In question you have mentioned that it will some value that will be received from some other activity. If still not clear, can you show what you have done to initialize `message`? Share the complete code – Sanjeet Feb 27 '17 at 18:31
  • That is my code `if (RecievedMessage.equals("hello")){ //change the imageView to hello.png }` – R.Jiny Feb 27 '17 at 18:48
  • replace this code with the answer and also change `message` to `RecievedMessage` – Sanjeet Feb 27 '17 at 18:53
  • OK and what should I write for the context, I mean do I need to declare it or import it??... Or something else – R.Jiny Feb 27 '17 at 18:57
  • If you are using this code in activity then replace context with `this`, for fragment you can replace context with `getActivity()` – Sanjeet Feb 27 '17 at 18:59