android以编程方式添加ImageView选择器

时间:2011-06-14 19:05:11

标签: android

我想以编程方式使用选择器状态而不是使用xml文件来更改ImageView背景(在我的情况下为渐变颜色)。

我希望将压缩和默认状态设置为我的ImageView

为了创建渐变背景,我使用以下代码:

 GradientDrawable gd = new GradientDrawable(
                    GradientDrawable.Orientation.BOTTOM_TOP,
                    new int[] {Color.parseColor(startColour), Color.parseColor(endColour)});

如何为此实现选择器?

由于

1 个答案:

答案 0 :(得分:6)

这是来自我的应用:

public static Drawable getButtonDrawableByScreenCathegory(Context con,
        ScreenCategory screenCategory, ButtonType buttonType) {

    int normalStateResID = (int) GXConstants.NOT_ID;
    int pressedStateResID = R.drawable.button_header_pressed;

    switch (screenCategory) {
    ...
    }

    Drawable state_normal = con.getResources()
            .getDrawable(normalStateResID).mutate();

    Drawable state_pressed = con.getResources()
            .getDrawable(pressedStateResID).mutate();

    StateListDrawable drawable = new StateListDrawable();

    drawable.addState(new int[] { android.R.attr.state_pressed },
            state_pressed);
    drawable.addState(new int[] { android.R.attr.state_enabled },
            state_normal);

    return drawable;
}

要为按钮设置背景,请致电:

button.setBackgroundDrawable(GXUtils.getButtonDrawableByScreenCathegory(
            this, mScreenCategory, ButtonType.MENU)