在代码中定义选择器

时间:2011-11-29 10:00:42

标签: android

我有以下选择器:

<selector xmlns:android="http://schemas.android.com/apk/res/android">
    <item>
        <shape android:shape="rectangle">
            <solid android:color="#00000" />
            <corners android:radius="10dp" />
            <stroke android:width="5px" android:color="#FFFFFF" />
        </shape>
    </item>

</selector>

我想在代码中定义。我已经成功了:

StateListDrawable states = new StateListDrawable();

float[] roundedCorner = new float[] { 10, 10, 10, 10, 10, 10, 10, 10 };
float[] innerRoundedCorner = new float[] { 5, 5, 5, 5, 5, 5, 5, 5 };
RectF inset = new RectF(5, 5, 5, 5);
RoundRectShape round = new RoundRectShape(roundedCorner, inset, innerRoundedCorner);        

ShapeDrawable shape = new ShapeDrawable(round);     
shape.getPaint().setColor(Color.WHITE);

states.addState(new int[] {}, shape);

button.setBackgroundDrawable(states);

这给了我一个带白边的按钮,但我无法设置按钮背景颜色。 这是如何在代码中实现的?

2 个答案:

答案 0 :(得分:2)

RoundRectShape可以在RectF上接受null,然后你将有一个填充的形状。 此外,当您使用状态时,您可以在选择器中指定属性:state_pressed,state_single等。

试试这段代码:

private static StateListDrawable getStateListDrawable(int color, Context context) {
    StateListDrawable stateListDrawable = new StateListDrawable();

    float[] roundedCorner = new float[]{4, 4, 4, 4, 4, 4, 4, 4};
    float[] innerRoundedCorner = new float[]{0, 0, 0, 0, 0, 0, 0, 0};
    RoundRectShape roundedShape = new RoundRectShape(roundedCorner, null, innerRoundedCorner);

    ShapeDrawable pressedDrawable = new ShapeDrawable(roundedShape);
    pressedDrawable.getPaint().setColor(context.getResources().getColor(R.color.default_bg));
    stateListDrawable.addState(new int[]{android.R.attr.state_pressed}, pressedDrawable);

    ShapeDrawable normalDrawable = new ShapeDrawable(roundedShape);
    normalDrawable.getPaint().setColor(context.getResources().getColor(color));
    stateListDrawable.addState(new int[]{}, normalDrawable);

    return stateListDrawable;
} 

答案 1 :(得分:0)

试试这段代码

StateListDrawable states = new StateListDrawable();

    float[] roundedCorner = new float[] { 10, 10, 10, 10, 10, 10, 10, 10 };
    float[] innerRoundedCorner = new float[] { 5, 5, 5, 5, 5, 5, 5, 5 };
    RectF inset = new RectF(0, 0, 0, 0);

    RoundRectShape round = new RoundRectShape(roundedCorner, inset, innerRoundedCorner);        
    LinearGradient lg = new LinearGradient(0, 0, 100, 100, Color.BLUE, Color.CYAN, TileMode.REPEAT);

    ShapeDrawable shape = new ShapeDrawable(round);
    shape.getPaint().setStyle(Style.FILL_AND_STROKE);
    //shape.getPaint().setColor(Color.WHITE);
    shape.getPaint().setShader(lg);

    states.addState(new int[] {}, shape);

    button.setBackgroundDrawable(shape);

当您定义在RoundRectShape中添加的RectF的inset对象时,传递0值,您获得完整的RoundRectShape

检查this帖子