【问题标题】:How to set BackgroundTintList of a button to default?如何将按钮的 BackgroundTintList 设置为默认值?
【发布时间】:2019-01-02 19:50:54
【问题描述】:

我正在使用以下行更改按钮的 BackgroundTintList 属性。

myButton.setBackgroundTintList(getColorStateList(R.color.green));

因此,我的 Button 将其颜色从灰色变为绿色,这就是我想要实现的目标。

我的问题是稍后我想设置按钮的原始灰色,但我不知道该怎么做。我试图在代码的最开头(在我更改它之前)获取按钮的 BackgroundTintList 属性,但以下行返回 NULL

ColorStateList buttonBackgroundTint = myButton.getBackgroundTintList();

将 BackgroundTintList 设置为绿色后,将其设置为 NULL 会将我的按钮更改为白色,而不是默认的灰色。

如何将我的按钮再次设置为灰色?

【问题讨论】:

  • 尝试将按钮的背景颜色设置为0

标签: java android button


【解决方案1】:

你可以试试这条线:

myButton.setBackgroundTintList(ColorStateList.valueOf(Color.parseColor("#d8d8d8")));

如果您想将按钮颜色更改回其默认/原始颜色。

【讨论】:

  • 这从技术上回答了我的问题,所以谢谢。我将继续寻找通用解决方案,因为如果默认色调与此不同,那么颜色常数再次不同。
【解决方案2】:

我还没有找到任何容易做到这一点的方法。我可以实现您的目标的唯一方法是保留原始背景 Drawable,创建它的克隆,手动为克隆着色,然后在这些新的可绘制对象之间来回切换。

private Drawable original;
private Drawable tinted;

@Override
protected void onCreate(Bundle savedInstanceState) {
    ...

    this.original = button.getBackground();
    this.tinted = button.getBackground().getConstantState().newDrawable().mutate();

    ColorStateList custom = getResources().getColorStateList(R.color.my_button, getTheme());
    tinted.setTintList(custom);

    ...
}

然后我可以写button.setBackground(original)button.setBackground(tinted) 在两者之间进行交换。

【讨论】:

    【解决方案3】:

    我刚刚创建了一个新的Button 并获得了backgroundTintList

    actionSearch.backgroundTintList = MaterialButton(requireContext()).backgroundTintList
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 2011-01-05
      • 1970-01-01
      • 2012-03-16
      • 2022-11-24
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多