【问题标题】:android add ImageView selector programmaticallyandroid以编程方式添加ImageView选择器
【发布时间】:2011-06-14 19:05:11
【问题描述】:

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

我希望 ImageView 处于按下状态和默认状态

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

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

我怎样才能为此实现选择器?

谢谢

【问题讨论】:

    标签: android


    【解决方案1】:

    这是来自我的应用程序:

    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)
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2010-09-29
      • 1970-01-01
      • 1970-01-01
      • 2020-04-20
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2012-04-28
      相关资源
      最近更新 更多