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>
1

3 Answers 3

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
Sign up to request clarification or add additional context in comments.

4 Comments

I found the following sample exceedingly useful because it also shows how to use 'false' states (with a leading minus symbol) heliodorj.blogspot.com/2009/04/…
what is the default state?
default state is as follows: stateListDrawable.addState(new int[] {}, new ColorDrawable(getResources().getColor(R.color.red)));
@SomeoneSomewhere thanks you so much, I've been searching for setting a state_activated="false" programmatically for hours !
4

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

Comments

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);

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.