从Java代码更改XML选择器(不可绘制)

时间:2012-12-03 06:21:47

标签: android xml selector statelistdrawable

我正在尝试创建一个通用的Custom Combobox库。

如何更改xml代码 - > java代码。

拜托,请提示我。

    <selector xmlns:android="http://schemas.android.com/apk/res/android">
    <item android:state_enabled="true" android:state_pressed="false">
        <shape android:shape="rectangle">            
<padding android:bottom="5dp" android:left="5dp" android:top="5dp" />
            <stroke android:width="1px" android:color="@color/textbox_border_color" />
            <solid android:color="@color/textbox_nomal_color" />
            <corners android:bottomRightRadius="15dp" />
        </shape>
    </item>
    <item android:state_enabled="true" android:state_pressed="true">
        <shape android:shape="rectangle">
            <padding android:bottom="5dp" android:left="5dp" android:top="5dp" />
            <stroke android:width="1px" android:color="@color/textbox_border_color" />
            <solid android:color="@color/textbox_pressed_color" />
            <corners android:bottomRightRadius="15dp" />            
        </shape>
    </item>
    <item android:state_enabled="false"><shape android:shape="rectangle">
            <padding android:bottom="5dp" android:left="5dp" android:top="5dp" />
            <stroke android:width="1px" android:color="@color/textbox_border_color" />
            <solid android:color="@color/textbox_disable_color" />
            <corners android:bottomRightRadius="15dp" />
        </shape>
    </item>
</selector>

1 个答案:

答案 0 :(得分:0)

使用StateListDrawable按代码选择seeting选择器:

StateListDrawable states = new StateListDrawable();
states.addState(new int[] {android.R.attr.state_pressed},
    getResources().getDrawable(R.drawable.pressed));
states.addState(new int[] {android.R.attr.state_focused},
    getResources().getDrawable(R.drawable.focused));
states.addState(new int[] { },
    getResources().getDrawable(R.drawable.normal));

imageView.setImageDrawable(states);  //YOUR IMAGE HERE
//AND FOR BUTTON
 button.setBackgroundDrawable(states);//FOR BUTTON

这可能会有所帮助