I have an ImageButton which on click i show a dialog box where users can either take a photo from the camera or choose from the gallery. On selecting image from either sources i setBitmap for that ImageButton to the image selected like this
SelectedPhoto = BitmapFactory.decodeFile(selectedImagePath);
DisplayPhoto.setImageBitmap(SelectedPhoto);
Now when some one has already selected an image and click the image again i want to show a different dialog which contains a third option “Remove Photo”.
What property of the image button should i check and against what ?
ImageButton in XML
<ImageButton
android:id="@+id/DisplayPhoto"
android:layout_width="95dip"
android:layout_height="95dip"
android:layout_marginRight="8dip"
android:background="@drawable/signup_photo_selector" android:scaleType="centerCrop" />
ImageButton Background XML
<?xml version="1.0" encoding="utf-8"?>
<selector xmlns:android="http://schemas.android.com/apk/res/android">
<item android:drawable="@drawable/signup_form_photo_selected" android:state_pressed="true"/>
<item android:drawable="@drawable/signup_form_photo"/>
</selector>
Would imgButton.getDrawable() work, since it returns null if no drawable has been assigned to the imagebutton?
If not, or if you don’t want to get the entire drawable just to see if it’s there, you can use a tag. imgButton.setTag(object) lets you store any object within the imagebutton… every time you set its background, you can tag a value that identifies whether its background was set. You could even use different values to differentiate whether you set its background using a camera or from the gallery, if that’s useful. When you want to see if the imagebutton has a background or not, use imgButton.getTag() to retrieve the object.
Edit. Here is how you would use setTag and getTag. I will use an Integer object as the ImageButton’s tag, where a value of 0 indicates no background has been set and a value of 1 indicates a background has been set. You can use an enum or final variables if you want to make the code a bit clearer, but using an Integer will work as an example.