【问题标题】:How can I modify a button's background for state pressed?如何为按下状态修改按钮的背景?
【发布时间】:2014-04-05 14:46:44
【问题描述】:

我正在为视力不好的人构建一个无障碍应用程序,用户可以在其中选择自己的颜色组合。出于这个原因,我需要根据他们的偏好以编程方式更改按钮的背景。

我想设置按钮未按下时的背景颜色和按下按钮时的不同颜色。但是我做 setBackgroundColor 会覆盖这两个值。

        ((Button) view).setBackgroundColor(customColor1);

如何在未按下按钮时设置 customColor1,在按下按钮时设置 customColor2?

【问题讨论】:

  • 你需要一个切换按钮之类的东西吗??

标签: android styles views


【解决方案1】:

试试这样的

Button btn = (Button) findViewById(R.id.button);

StateListDrawable stateListDrawable = new StateListDrawable();
stateListDrawable.addState(new int[] {android.R.attr.state_pressed}, new ColorDrawable(getResources().getColor(R.color.red)));
stateListDrawable.addState(new int[] {-android.R.attr.state_pressed}, new ColorDrawable(getResources().getColor(R.color.green)));

btn.setBackgroundDrawable(stateListDrawable);

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2012-07-03
    • 1970-01-01
    • 2021-07-10
    • 1970-01-01
    • 1970-01-01
    • 2011-12-30
    • 1970-01-01
    相关资源
    最近更新 更多