Android以编程方式创建选择器

时间:2015-08-26 12:08:26

标签: android

如何以编程方式创建选择器?
我有一个xml选择器,分配给TabWidget作为Tab indicator color

<?xml version="1.0" encoding="utf-8"?>
<selector xmlns:android="http://schemas.android.com/apk/res/android">
    <!-- Non focused states -->
    <item android:state_focused="false" android:state_selected="false" android:state_pressed="false" android:drawable="@drawable/bg_tab_unselected" />
    <item android:state_focused="false" android:state_selected="true"  android:state_pressed="false" android:drawable="@drawable/bg_tab_selected" />

    <!-- Focused states -->
    <item android:state_focused="true" android:state_selected="false" android:state_pressed="false" android:drawable="@drawable/bg_tab_unselected_focused" />
    <item android:state_focused="true" android:state_selected="true"  android:state_pressed="false" android:drawable="@drawable/bg_tab_selected_focused" />

    <!-- Pressed -->
    <!--    Non focused states -->
    <item android:state_focused="false" android:state_selected="false" android:state_pressed="true" android:drawable="@drawable/bg_tab_unselected_pressed" />
    <item android:state_focused="false" android:state_selected="true"  android:state_pressed="true" android:drawable="@drawable/bg_tab_selected_pressed" />

    <!--    Focused states -->
    <item android:state_focused="true" android:state_selected="false" android:state_pressed="true" android:drawable="@drawable/bg_tab_unselected_pressed" />
    <item android:state_focused="true" android:state_selected="true"  android:state_pressed="true" android:drawable="@drawable/bg_tab_selected_pressed" />
</selector>

有没有办法动态创建上面的xml代码?

2 个答案:

答案 0 :(得分:37)

你可以像这样使用它:

public static StateListDrawable makeSelector(int color) {
    StateListDrawable res = new StateListDrawable();
    res.setExitFadeDuration(400);
    res.setAlpha(45);
    res.addState(new int[]{android.R.attr.state_pressed}, new ColorDrawable(color));
    res.addState(new int[]{}, new ColorDrawable(Color.TRANSPARENT));
    return res;
}

然后:

view.setBackground(makeSelector(Color.RED));

答案 1 :(得分:2)

您可以直接创建StateListDrawable并使用addState添加您在XML中定义的状态:

StateListDrawable d = new StateListDrawable();

[...]

int[] sFocusedSelected = { android.R.attr.state_focused, android.R.attr.state_selected };
Drawable dFocusedSelected = getDrawable(R.drawable.bg_tab_selected_focused);
d.addState(sFocusedSelected, dFocusedSelected);

[...]

同样的规则适用于XML

  

选择不是基于“最佳匹配”,而是基于符合州最低标准的第一项。