【问题标题】:How to get background color of button. On click action depends on background color [closed]如何获取按钮的背景颜色。点击操作取决于背景颜色[关闭]
【发布时间】:2015-02-03 13:03:58
【问题描述】:

从 color.xml 将背景颜色设置为控件(按钮)...... 我需要按钮的背景颜色来检查该时间分配的颜色。

【问题讨论】:

    标签: android button colors onclick


    【解决方案1】:

    这样使用:

    很容易把它做成 Drawable

    Button button = (Button) findViewById(R.id.my_button);
    Drawable buttonBackground = button.getBackground();
    

    如果你知道这是一种颜色,那么你可以试试

    ColorDrawable buttonColor = (ColorDrawable) button.getBackground();
    

    如果您使用的是 Android 3.0+,则可以获取颜色的资源 ID。

    int colorId = buttonColor.getColor();
    

    并将其与您分配的颜色进行比较,即。

    if (colorID == R.color.green) {
      log("color is green");
    }
    

    【讨论】:

    • 我花了很长时间才发现需要将背景转换为 ColorDrawable。谢谢。
    猜你喜欢
    • 1970-01-01
    • 2016-08-12
    • 1970-01-01
    • 2022-01-02
    • 2011-12-26
    • 2018-04-25
    • 2013-06-24
    • 1970-01-01
    • 2020-11-11
    相关资源
    最近更新 更多