我正在尝试更改按钮的背景颜色。我在模拟器上使用 SDK 21 的 Kotlin。
View 和 Button 在布局 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"
/>
Run Code Online (Sandbox Code Playgroud)
设置颜色的 API 似乎不起作用:
showButton.setBackgroundColor(0xff60a0e0.toInt()) <-- doesnt work
Run Code Online (Sandbox Code Playgroud)
有效的是:
myview.setBackgroundColor(0xff60a0e0.toInt()) <-- works, exact background color
showButton.setTextColor(0xff000050.toInt()) <-- works, exact text color
Run Code Online (Sandbox Code Playgroud)
经过进一步尝试后,我似乎只能设置按钮的 Alpha 通道,而不能设置颜色:
setBackgroundColor( 0xff000000.toInt()) <-- works, opaque
setBackgroundColor( 0x00000000.toInt()) <-- works, transparent
Run Code Online (Sandbox Code Playgroud)
同样的事情还有:
showButton.setBackgroundColor(Color.GREEN) <-- doesnt work, button is opaque but not green
showButton.setBackgroundColor(Color.TRANSPARENT) <-- works, button is transparent
Run Code Online (Sandbox Code Playgroud)
任何想法?我是否错过了其他答案或文档中的某些内容?
这是完整的布局,它用于填充片段(如果重要的话):
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android" …Run Code Online (Sandbox Code Playgroud) android android-button kotlin material-components material-components-android