Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Android button states programmatically in Java (not XML)

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>
like image 836
Cris Avatar asked Dec 07 '11 06:12

Cris


2 Answers

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
like image 110
Tang Ke Avatar answered Sep 27 '22 18:09

Tang Ke


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

like image 29
Peter Knego Avatar answered Sep 27 '22 18:09

Peter Knego