我正在尝试更改按钮的背景色。我在模拟器上使用SDK 21的Kotlin中。
在布局XML文件中声明了View和Button
<View
android:id="@+id/myview"
android:layout_width="64dp"
android:layout_height="32dp"
/>
<Button
android:id="@+id/showButton"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="12dp"
android:text="test"
/>
设置颜色的API似乎无效:
showButton.setBackgroundColor(0xff60a0e0.toInt()) <-- doesnt work
起作用的是:
myview.setBackgroundColor(0xff60a0e0.toInt()) <-- works, exact background color
showButton.setTextColor(0xff000050.toInt()) <-- works, exact text color
经过进一步尝试后,看来我只能设置按钮的Alpha通道,而不能设置颜色:
setBackgroundColor( 0xff000000.toInt()) <-- works, opaque
setBackgroundColor( 0x00000000.toInt()) <-- works, transparent
同样也是这样:
showButton.setBackgroundColor(Color.GREEN) <-- doesnt work, button is opaque but not green
showButton.setBackgroundColor(Color.TRANSPARENT) <-- works, button is transparent
任何的想法?我是否错过了其他答案或文档中的内容?
这是完整的布局,如果需要的话,它用来给片段充气:
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="match_parent"
android:layout_height="match_parent"
xmlns:app="http://schemas.android.com/apk/res-auto"
android:orientation="vertical">
<LinearLayout
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:orientation="horizontal">
<View
android:id="@+id/myview"
android:layout_width="64dp"
android:layout_height="32dp"
/>
<Button
android:id="@+id/showButton"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="12dp"
android:text="test"
/>
</LinearLayout>
<androidx.recyclerview.widget.RecyclerView
android:id="@+id/dictionaryEntryRecyclerView"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:scrollbars="vertical"
app:layoutManager="LinearLayoutManager"
/>
</LinearLayout>
最佳答案
由于您使用的是Theme.MaterialComponents.Light.DarkActionBar
主题,因此请检查doc,然后仅将 MaterialButton
与 app:backgroundTint
属性一起使用:
<com.google.android.material.button.MaterialButton
android:layout_width="wrap_content"
android:layout_height="wrap_content"
app:backgroundTint="@color/color_selector"
android:textColor="#FFF"
android:text="BUTTON"
/>
其中color_selector可以是颜色或选择器。就像是:
<selector xmlns:android="http://schemas.android.com/apk/res/android">
<item android:color="@color/..." android:state_enabled="true"/>
<item android:alpha="0.12" android:color="@color/..."/>
</selector>