Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Android ImageButton with a selected state?

If I was using an ImageButton with a selector for its background, is there a state I can change which will make it change its appearance? Right now I can get it to change images when pressed, but there seems to be no "highlighted" or "selected" or similar state which lets me toggle its appearance at will.

Here's my XML; it only changes appearance when pressed.

 <selector xmlns:android="http://schemas.android.com/apk/res/android"> <item android:state_focused="true" android:state_pressed="false" android:drawable="@drawable/map_toolbar_details_selected" /> <item android:state_focused="true" android:state_pressed="true" android:drawable="@drawable/map_toolbar_details_selected" /> <item android:state_focused="false" android:state_pressed="true" android:drawable="@drawable/map_toolbar_details_selected" /> <item android:drawable="@drawable/map_toolbar_details" /> 

like image 491
Joren Avatar asked Apr 09 '10 01:04

Joren


1 Answers

This works for me:

<?xml version="1.0" encoding="utf-8"?> <selector xmlns:android="http://schemas.android.com/apk/res/android">     <!-- NOTE: order is important (the first matching state(s) is what is rendered) -->     <item          android:state_selected="true"          android:drawable="@drawable/info_icon_solid_with_shadow" />     <item          android:drawable="@drawable/info_icon_outline_with_shadow" />  </selector> 

And then in java:

//assign the image in code (or you can do this in your layout xml with the src attribute) imageButton.setImageDrawable(getBaseContext().getResources().getDrawable(R.drawable....));  //set the click listener imageButton.setOnClickListener(new OnClickListener() {      public void onClick(View button) {         //Set the button's appearance         button.setSelected(!button.isSelected());          if (button.isSelected()) {             //Handle selected state change         } else {             //Handle de-select state change         }      }  }); 

For smooth transition you can also mention animation time:

<selector xmlns:android="http://schemas.android.com/apk/res/android" android:exitFadeDuration="@android:integer/config_mediumAnimTime"> 
like image 70
joshrl Avatar answered Sep 21 '22 17:09

joshrl