相关疑难解决方法(0)

Android:如何以编程方式更新选择器(StateListDrawable)

我想以编程方式更新按钮的选择器.

我可以使用下面给出的xml文件来完成此操作

<?xml version="1.0" encoding="UTF-8"?>
<selector xmlns:android="http://schemas.android.com/apk/res/android">
   <item android:state_enabled="false"
         android:drawable="@drawable/btn_off" />
   <item android:state_pressed="true"
         android:state_enabled="true" 
         android:drawable="@drawable/btn_off" />
   <item android:state_focused="true"
         android:state_enabled="true" 
         android:drawable="@drawable/btn_on" />
   <item android:state_enabled="true" 
         android:drawable="@drawable/btn_on" />
</selector>
Run Code Online (Sandbox Code Playgroud)

我想以编程方式做同样的事情.我试过下面给出的东西

private StateListDrawable setImageButtonState(int index)
{
    StateListDrawable states = new StateListDrawable();

    states.addState(new int[] {android.R.attr.stateNotNeeded},R.drawable.btn_off); 
    states.addState(new int[] {android.R.attr.state_pressed, android.R.attr.state_enabled},R.drawable.btn_off);
    states.addState(new int[] {android.R.attr.state_focused, android.R.attr.state_enabled},R.drawable.btn_on);
    states.addState(new int[] {android.R.attr.state_enabled},R.drawable.btn_on);

    return states;
}
Run Code Online (Sandbox Code Playgroud)

但它没有用.

以及如何设置android:state_enabled="false"android:state_enabled="true"编程.

android state button

60
推荐指数
4
解决办法
5万
查看次数

标签 统计

android ×1

button ×1

state ×1