android - Android如何在Button上设置背景颜色
问题描述
我正在尝试更改按钮的背景颜色。我在模拟器上使用 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>
解决方案
mButton.setBackgroundColor(ContextCompat.getColor(mContext, R.color.xxx));
推荐阅读
- java - 例如,Ionic 和 Android Studio 都无法下载 https://services.gradle.org/distributions/gradle-4.10.3-all.zip 并导致构建崩溃
- greasemonkey - 如何使用 Tampermonkey 脚本更改特定站点的样式?
- java - BAD : JAVA Math.sqrt(i) 趋于 0
- php - 基于PHP中的值对数组进行排序
- annotations - 如何将带注释的公理序列化为 RDF 形式?
- android - 构建 Flutter Android 应用时 AppCenter 构建崩溃
- sitecore - 单击按钮生成自定义 Sitecore 日志
- android - 通知代码添加到服务中但不起作用
- php - 如何将慢查询追溯到 WordPress/WooCommerce 中的代码
- php - PHP 法尔康。在模型中使用 postgres nextval(sequence)