Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

how to get the source of ImageView in order to change it?

Tags:

I know that changing the ImageView resource is not big deal just using myImageView.setImageResource(mynewImageDrawable)

but what I want to do is to check the current ImageSource before changing it.

basically, I want to implement my own group radio buttons using imageViews. so every time any imageView is clicked, the oncliked event method will change the Image Resources of my group.

and sorry for my poor English.

regards, redsea

like image 421
Red Sea Avatar asked May 23 '12 19:05

Red Sea


Video Answer


2 Answers

There is no getDrawableId function so you'll need to do something like set a tag for the ImageView when you change its drawable. For instance, set the drawable id as a tag for the ImageView so you could just get the drawable id from the tag.

How to do that?

I'd say 90% of the time, your views wont have any tag on them, so the easiest way is to assume your tag is the only tag:

myImageView.setTag(R.drawable.currentImage);    //When you change the drawable int drawableId = (Integer)myImageView.getTag(); //When you fetch the drawable id 

What if I already have a tag on my view

Android views can host multiple tags at the same time, as long as they have a unique identifier. You'd need to create a unique id resource and add it as the first argument to the setTag method call. Leaving the code like this:

myImageView.setTag(R.id.myTagId, R.drawable.currentImage); //Set int drawableId = (Integer)myImageView.getTag(R.id.myTagId); 
like image 128
Juan Cortés Avatar answered Oct 20 '22 14:10

Juan Cortés


To get Image source, you can use Drawable.ConstantState. For example, in my problem I was implementing a button click to change the ImageView. I created two Drawable.ConstantState objects and compared them. The code is given below:

ImageView myImg=(ImageView) findViewById(R.id.myImg);         Drawable.ConstantState imgID = myImg.getDrawable().getConstantState();         Drawable.ConstantState imgID2 = getDrawable(R.drawable.otherImage).getConstantState();         if(imgID!=imgID2)         {             // Block of Code         }         else // Other Block of Code  
like image 21
090 Avatar answered Oct 20 '22 14:10

090