我正在尝试更改按钮的背景颜色。我在模拟器上使用Kotlin和SDK 21。
布局XML文件中声明了一个视图和一个按钮。
<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>