10

How does one define Android button image for the "state_pressed" "android:state_focused" in Java?

For example, how would one accomplish the equivalent in Java for the XML from

http://developer.android.com/reference/android/widget/ImageButton.html

 <?xml version="1.0" encoding="utf-8"?>
 <selector xmlns:android="http://schemas.android.com/apk/res/android">
     <item android:state_pressed="true"
           android:drawable="@drawable/button_pressed" /> <!-- pressed -->
     <item android:state_focused="true"
           android:drawable="@drawable/button_focused" /> <!-- focused -->
     <item android:drawable="@drawable/button_normal" /> <!-- default -->
 </selector>
Cris
  • 464
  • 1
  • 3
  • 15

3 Answers3

14

Just use addState method of StateListDrawable

StateListDrawable stateListDrawable = new StateListDrawable();
stateListDrawable.addState(new int[] {android.R.attr.state_pressed}, 
      getResources().getDrawable(R.drawable.phone));

You can use constants below for the first parameter of this method

android.R.attr.state_accelerated
android.R.attr.state_activated
android.R.attr.state_active
android.R.attr.state_drag_can_accept
android.R.attr.state_drag_hovered
android.R.attr.state_enabled
android.R.attr.state_first
android.R.attr.state_focused
android.R.attr.state_hovered
android.R.attr.state_last
android.R.attr.state_middle
android.R.attr.state_pressed
android.R.attr.state_selected
android.R.attr.state_single
android.R.attr.state_window_focused
Tang Ke
  • 1,508
  • 12
  • 12
4

Create an instance of StateListDrawable and then assign it with imagebutton.setImageDrawable(stateDrawable).

Peter Knego
  • 79,991
  • 11
  • 123
  • 154
1

10x to Tang Ke, I`m using this for different list item color whit selection color.

selected state

stateListDrawable.addState(new int[] {android.R.attr.state_pressed}, 
  new ColorDrawable(getResources().getColor(R.color.alpha_blue500)));

default state

stateListDrawable.addState(new int[] {}, 
  new ColorDrawable(getResources().getColor(R.color.red)));

Here you can change color for different state of the row item (ex. paid vs free)

set state to custom layout row item in list adapter

holder.relativeLayout.setBackgroundDrawable(stateListDrawable);
Vasil Valchev
  • 5,701
  • 2
  • 34
  • 39