首页
学习
活动
专区
圈层
工具
发布
社区首页 >问答首页 >StateListDrawable不工作

StateListDrawable不工作
EN

Stack Overflow用户
提问于 2012-10-05 12:09:37
回答 1查看 8.8K关注 0票数 3

我正在尝试以编程方式将StateListDrawable设置为库项目的自定义视图的背景。我正在做的事情是:

代码语言:javascript
复制
final TypedArray a = getContext().obtainStyledAttributes(attrs,
            R.styleable.ActionBar);
    int firstColor = a.getColor(
            R.styleable.ActionBar_backgroundGradientFirstColor, 0xff000000);
    int secondColor = a
            .getColor(R.styleable.ActionBar_backgroundGradientSecondColor,
                    0xff000000);
    int textViewColor = a.getColor(R.styleable.ActionBar_titleColor,
            0xffffffff);
    int onClickColor = a.getColor(
            R.styleable.ActionBar_backgroundClickedColor, 0xff999999);
    a.recycle();

    StateListDrawable sld = new StateListDrawable();
    GradientDrawable drawable = new GradientDrawable(
            Orientation.TOP_BOTTOM, new int[] { firstColor, secondColor });
    sld.addState(new int[] { android.R.attr.state_enabled },
            new ColorDrawable(onClickColor));
    sld.addState(new int[] { android.R.attr.state_pressed }, drawable);

    action2.setBackgroundDrawable(sld);
    action3.setBackgroundDrawable(sld);
    actionBack.setBackgroundDrawable(sld);
    pb.setBackgroundDrawable(drawable);
    tv.setBackgroundDrawable(drawable);
    tv.setTextColor(textViewColor);

但是,这不起作用:它总是绘制启用状态。当我按按下按钮时,我希望它画出按下的状态。我做错了什么?

EN

回答 1

Stack Overflow用户

回答已采纳

发布于 2012-10-05 13:58:08

我想按钮在按下的时候仍然是启用的?

您可以尝试倒序:

代码语言:javascript
复制
sld.addState(new int[] { android.R.attr.state_pressed }, drawable);
sld.addState(new int[] { android.R.attr.state_enabled },
        new ColorDrawable(onClickColor));

可能正在绘制第一个当前有效的状态。

如果在按下时需要一个不同的背景,对于所有其他情况,也可以使用另一个背景:

代码语言:javascript
复制
sld.addState(new int[] { android.R.attr.state_pressed }, drawable);
sld.addState(new int[] { StateSet.WILD_CARD },
        new ColorDrawable(onClickColor));

添加:我刚刚测试了这个,下面的测试代码适用于我:

代码语言:javascript
复制
Button testButton = new Button(context);
            testButton.setText("Test");
            StateListDrawable sld = new StateListDrawable();
            GradientDrawable drawable = new GradientDrawable(
                    Orientation.TOP_BOTTOM, new int[] { Color.BLUE, Color.RED });
            sld.addState(new int[] { android.R.attr.state_pressed }, drawable);
            sld.addState(StateSet.WILD_CARD, new ColorDrawable(Color.YELLOW));
            testButton.setBackgroundDrawable(sld);          
            mainLayout.addView(testButton);
票数 20
EN
页面原文内容由Stack Overflow提供。腾讯云小微IT领域专用引擎提供翻译支持
原文链接:

https://stackoverflow.com/questions/12745968

复制
相关文章

相似问题

领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档