casillas
casillas

Reputation: 16813

Change Selected ImageButton Background

I have the following implementation in the iOS and it works very well.

private void States(UIButton button, UIImage unselectedImage, UIImage selectedImage) 
{
    button.SetImage (unselectedImage, UIControlState.Normal);
    button.SetImage (selectedImage, UIControlState.Selected);
    button.SetImage (selectedImage, UIControlState.Selected | UIControlState.Highlighted);
}

I am trying to implement same functionality in the Android.Xamarin, I have implemented ImageButton rather than Button. I would like to know how to change background of selected or unselected button in Android.Xamarin?

private void States(ImageButton button, string unselectedImage, string selectedImage) 
{
    // I could not able to change the background of the selected/unselected UmageButton
}

I have came across the following site (http://developer.xamarin.com/recipes/android/controls/imageview/display_an_image/), however there are two properties (button+imageView) are defined to change button background image. I think that ImageButton should include all of these features in all-in-one.


The following xml, it only highlights one, it does not remain highlighted.I want to remain highlighted.

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

Upvotes: 1

Views: 582

Answers (1)

Glorfindel
Glorfindel

Reputation: 22651

You can do this with selectors.

The idea is that you define a different drawable for each state:

  <item
      android:state_enabled="false"
      android:drawable="@drawable/disabledbutton" />
  <item
      android:state_pressed="true"
      android:state_enabled="true"
      android:drawable="@drawable/pressedbutton" />
  <item
      android:state_focused="true"
      android:state_enabled="true"
      android:drawable="@drawable/focusedbutton" />
  <item
      android:state_enabled="true"
      android:drawable="@drawable/normalbutton" />

Upvotes: 1

Related Questions