1

关于 SO 已经有很多类似的问题,比如这个,但答案不适用(不再适用?)。

这就是我创建按钮的方式:

<Button
    android:id="@+id/myId"
    android:layout_width="wrap_content"
    android:layout_height="wrap_content"
    app:layout_constraintBottom_toBottomOf="parent"
    app:layout_constraintLeft_toLeftOf="parent"
    app:layout_constraintRight_toRightOf="parent" />

这就是我改变颜色的方式:

myButton.getBackground().setColorFilter(lightSalmon, PorterDuff.Mode.SRC);

到目前为止,一切都很好。现在我想把它改回默认值。这是我到目前为止所尝试的:

myButton.getBackground().clearColorFilter();

使按钮背景变为白色而不是默认的灰色。如同:

myButton.getBackground().setColorFilter(null);

这完全改变了按钮的外观:

myButton.setBackgroundResource(android.R.drawable.btn_default);

它确实重置了颜色,但按钮看起来完全不同。也不是我想要的。

setTint()在 API 中找到了,但我没有尝试过,因为它需要 API 级别 21(我在 15 级)。有向后兼容的方式setTint()吗?

尝试以编程方式记住默认颜色也不起作用,因为getColorFilter()还需要 API 级别 21。(setColorFilter()另一方面,自 API 级别 1 以来就存在)。

我能想到的另一个选择是只应用默认灰色(如果我可以确定它的值)。但我担心这可能会有偏见:默认灰色在其他手机上可能会有所不同,与其他 Android 版本、其他主题和样式...

我还有什么其他选择?

4

1 回答 1

-1

使用透明

findViewById(R.id.button_id).setBackgroundColor(Color.TRANSPARENT);

它应该工作。

于 2019-04-14T16:44:11.063 回答