如何在android中重用颜色不同的按钮选择器?

时间:2014-10-20 11:59:08

标签: android

有按钮的选择器文件:

<?xml version="1.0" encoding="utf-8"?>
<selector xmlns:android="http://schemas.android.com/apk/res/android">

<item android:state_pressed="true">
    <shape>
        <solid android:color="#686b70"/>

        <stroke android:width="1dip" android:color="#595b61" />

        <corners android:radius="8dip" />
    </shape>
</item>

<item android:state_focused="true">
    <shape>
        <solid android:color="#686b70"/>

        <stroke android:width="1dip" android:color="#595b61" />

        <corners android:radius="8dip" />
    </shape>

</item>
<item>
    <shape>
        <solid android:color="#868c95"/>

        <stroke android:width="1dip" android:color="#7c818b" />

        <corners android:radius="8dip" />
    </shape>
</item>

我只需要更改solid和stroke的android:color来创建一个新的选择器。所以我想知道有没有办法将这个选择器重用于不同颜色的按钮。

1 个答案:

答案 0 :(得分:1)

请参阅这些代码段可能会帮助您

创建形状运行时

ShapeDrawable shapeSelected = new ShapeDrawable(new RectShape());
        shapeSelected.getPaint().setColor(Color.RED);
        shapeSelected.getPaint().setStyle(Paint.Style.STROKE);
        shapeSelected.getPaint().setStrokeWidth(1);

        ShapeDrawable shapeNormal = new ShapeDrawable(new RectShape());
        shapeSelected.getPaint().setColor(Color.WHITE);
        shapeSelected.getPaint().setStyle(Paint.Style.STROKE);
        shapeSelected.getPaint().setStrokeWidth(1);

在运行时创建选择器

StateListDrawable states =new StateListDrawable();
    Resources res = getResources();
    states.addState(new int[] {android.R.attr.state_pressed},shapeSelected);
    states.addState(new int[] {android.R.attr.state_focused}, shapeSelected);
    states.addState(new int[] {}, shapeNormal);

设置为观看背景

yourButton.setBackground(states);