Android按钮在Java(不是XML)中以编程方式声明

Cri*_*ris 10 user-interface android

如何在Java中为"state_pressed""android:state_focused"定义Android按钮图像?

例如,如何在Java中完成XML的等效项

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>
Run Code Online (Sandbox Code Playgroud)

Tan*_* Ke 13

只需使用StateListDrawable的addState方法

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

您可以使用下面的常量作为此方法的第一个参数

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
Run Code Online (Sandbox Code Playgroud)

  • 我发现以下示例非常有用,因为它还显示了如何使用'false'状态(带有前导减号)http://heliodorj.blogspot.com/2009/04/androids-statelistdrawable-example.html (3认同)

Pet*_*ego 4

创建 的实例StateListDrawable,然后将其分配给imagebutton.setImageDrawable(stateDrawable)