Checking Imageview Resource On Actionlistener Rather Than The Id Of The Imageview
I have 16 imageview, each set to onBtnClick as a listner, inside this method it checks whether the imageview id corresponds to a specific id, I need to change this so it checks the
Solution 1:
You can use tags to achieve this:
When creating your ImageView (in code or in XML), define a tag:
android:tag = "tag"
OR
Object tag = (Object) newInteger(R.drawable.img1);
imageView.setTag(tag);
Then retrieve the tag before you need it by:
Object tag = imageView.getTag();
int drawableId = Integer.parseInt(tag.toString());
if( drawableId == R.drawable.img1 ) {
....
}
Good luck!
Solution 2:
There is no way to do this directly with an imageView. There is however nothing stopping you from subclassing imageView and adding the required functionality. For example:
import android.content.Context;
import android.util.AttributeSet;
import android.widget.ImageButton;
publicclassMyImageButtonextendsImageButton {
privatestaticfinalStringANDROID_NAME_SPACE="http://schemas.android.com/apk/res/android";
privateintmDrawableResId= -1;
publicMyImageButton(Context context) {
super(context);
// TODO Auto-generated constructor stub
}
publicMyImageButton(Context context, AttributeSet attrs) {
super(context, attrs);
mDrawableResId = attrs.getAttributeResourceValue(ANDROID_NAME_SPACE, "src", -1);
}
publicMyImageButton(Context context, AttributeSet attrs, int defStyle) {
super(context, attrs, defStyle);
mDrawableResId = attrs.getAttributeResourceValue(ANDROID_NAME_SPACE, "src", -1);
}
@OverridepublicvoidsetImageResource(int resId){
super.setImageResource(resId);
mDrawableResId = resId;
}
publicintgetDrawableResId(){
return mDrawableResId;
}
}
This catches setting the drawable directly and from XML.
(diclaimer: I have never tried this however it should do exactly what you want. The example above does work in the emulator. If anyone has any opinions on this approach I would love to hear them.)
Post a Comment for "Checking Imageview Resource On Actionlistener Rather Than The Id Of The Imageview"