如何将按钮的背景色重置为默认的灰色?

时间:2018-12-22 20:24:06

标签: android

SO上已经有许多类似的问题,例如this one,但是答案不再适用(不再是?)。

这是我创建按钮的方式:

<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);

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

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

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

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

我还有什么其他选择?

1 个答案:

答案 0 :(得分:-1)

使用透明

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

应该可以。

相关问题