【问题标题】:Android programmatically change background of ButtonAndroid以编程方式更改按钮的背景
【发布时间】:2020-05-15 04:48:14
【问题描述】:

我无法在我的活动中更改按钮的背景。这是一个以形状为背景的基本按钮。

在我的 main.xml 中,我的 RelativeLayout 看起来像这样:

<Button
    android:id="@+id/mybtn"
    android:background = "@drawable/rounded_button"
    android:elevation="0dp" />

在我的 MainActivity 中,我尝试像这样更改按钮:

    Button btn = findViewById(R.id.mybtn);
    btn.setBackgroundColor(Color.RED);

但它说:

无法解析方法 setBackgroundColor

【问题讨论】:

标签: android android-layout android-button


【解决方案1】:

试试这个:

Button b = ...;
int color = ...;
...
CompoundButtonCompat.setButtonTintList(button, ColorStateList.valueOf(color));

Compat 库检查兼容性并消除 Android 碎片带来的大部分问题。

您可以尝试通过使用 set background color 方法调用兼容性库来设置背景,但我更喜欢并且可能常见的用法是在来自 appcompat 和材料设计库的组件上调用 tint 方法。

希望这会有所帮助。

BR

【讨论】:

    【解决方案2】:

    我猜你必须改变你的drawable的背景

    Drawable mDrawable = AppCompatResources.getDrawable(context, R.drawable. rounded_button); 
    Drawable wrappedDrawable = DrawableCompat.wrap(mDrawable);
    DrawableCompat.setTint(wrappedDrawable, Color.RED);   
    

    【讨论】:

    • 没有改变颜色
    【解决方案3】:

    您必须将 setBackgroundColor 更改为 setBackground。

    Button btn = findViewById(R.id.mybtn); btn.setBackground(Color.RED);
    

    【讨论】:

      【解决方案4】:

      您必须将 setBackgroundColor 更改为 setBackground。

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

      试试下面的代码

      button.setBackgroundResource(ContextCompat.getColor(MainActivity,this,R.color.red));
      

      【讨论】:

        猜你喜欢
        • 2011-03-07
        • 1970-01-01
        • 2013-09-12
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        相关资源
        最近更新 更多