【问题标题】:How do you get the background color of a button?你如何获得按钮的背景颜色?
【发布时间】:2021-08-12 06:15:57
【问题描述】:

如何获得按钮的背景颜色?我尝试了以下方法:

 public class MainActivity extends AppCompatActivity {

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);
        Button btn1 = findViewById(R.id.button);
        btn1.setBackgroundColor(getResources().getColor(R.color.red));
        //color red is added to colors.xml <color name="red">#FF0000</color>

        btn1.setOnClickListener(v -> {

          ColorDrawable btnColor = (ColorDrawable) btn1.getBackground();

          int clr = btnColor.getColor();

          if (clr == getResources().getColor(R.color.red)) {
              String line = "it's red";
              btn1.setText(line);
            }
        });
    }
}

当我点击按钮时,应用程序关闭,我得到了这个

 java.lang.ClassCastException: android.graphics.drawable.RippleDrawable cannot be cast to android.graphics.drawable.ColorDrawable

谁能解释我做错了什么?

【问题讨论】:

  • 检查this
  • 您是否在应用中使用 MaterialComponents 主题?
  • @MohammadAbdulAlim 我现在读一读,谢谢。
  • @GabrieleMariotti 是的,我在我的应用程序中使用了 MaterialComponents 主题,这是导致问题的原因吗?

标签: java android android-drawable android-button rippledrawable


【解决方案1】:
ColorDrawable buttonColor = (ColorDrawable) button.getBackground();
int colorId = buttonColor.getColor();
if (colorID == R.color.green) {
  log("color is green");
}

使用上面你可以找到一个按钮颜色。

【讨论】:

  • 由于某种原因它不适用于 android studio?
  • @jason 你找到解决办法了吗?
【解决方案2】:

您可以将其作为可绘制对象:

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

如果它是一种颜色,你可以这样做:

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

取出颜色的资源id:

Int color = btnColor.getColor();

然后将其与您的颜色进行比较:

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

【讨论】:

  • 对不起,我对 Java 和 android 工作室很陌生,但不是你发布的内容,除了 if 语句,我的设置按钮的文本而不是发布到'日志'?
【解决方案3】:

由于您使用的是MaterialComponents 主题,因此您的Button 在运行时会被MaterialButton 替换。

使用 setBackgroundTintList 代替 setBackgroundColor 并使用 getBackgroundTintList() 检索 ColorStateList

类似:

    MaterialButton button = findViewById(R.id.button);
    button.setBackgroundTintList(ColorStateList.valueOf(ContextCompat.getColor(this, R.color.red600)));
    ColorStateList colorStateList = button.getBackgroundTintList();

    int defaultColor = colorStateList.getColorForState(
            new int[] { android.R.attr.state_enabled},0);

【讨论】:

    猜你喜欢
    • 2018-07-27
    • 2016-08-12
    • 1970-01-01
    • 1970-01-01
    • 2013-06-24
    • 1970-01-01
    • 2022-01-02
    • 2020-08-19
    • 2013-08-06
    相关资源
    最近更新 更多