android - Android button setBackgroundColor 改变按钮大小
问题描述
我以编程方式创建 android 按钮,并将这个按钮放在 TableRow 中,一切正常,但是当我更改背景颜色时,彩色按钮不尊重大小,因为它没有颜色:
我的代码是:
val btn = Button(this)
btn.isEnabled = false
btn.setBackgroundColor(Color.RED)
btn.layoutParams = TableRow.LayoutParams(150, 150)
当我不使用时setBackgroundColor
,尺寸是正确的。
我不明白为什么尺寸会改变,有没有办法只改变按钮的默认灰色,而不改变尺寸。
解决方案
按钮的默认背景不是纯色,而是具有内置填充和边距的图形(例如九块位图)。因此,当您用颜色替换该背景图像时,所有内置的填充和边距都会被丢弃。
与其设置背景颜色,setBackgroundColor()
不如尝试使用setBackgroundTintList()
which 应该用您选择的颜色为现有背景图像着色。
或者,您需要在将背景更改为纯红色后手动设置边距和填充,这比在布局 XML 文件中通过代码执行的操作要痛苦得多。
示例布局文件:
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="match_parent"
android:layout_height="match_parent">
<Button
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="Red Button"
android:backgroundTint="#a00"
android:textColor="#fff" />
<Button
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="Default Button" />
</LinearLayout>
推荐阅读
- node.js - 如何在 Node.js 应用程序中自动重新加载更新的 SSL 证书
- python - mysql中持续时间的唯一值
- java - Android - 如何在不使用 Intent 的情况下发送 ArrayList?
- java - Hibenate“参数值与预期类型不匹配”
- python-3.x - 我该如何解决这个错误?你应该注意什么?
- python - Waf 配置错误,由于某种原因找不到 pyembed
- database - 猫鼬 $literal 在查找方法投影中
- r - 根据条件创建新列
- reactjs - React 在 Redux 中存储 Ref 元素
- mysql - 如果 MySQL INSERT 查询中不存在,则自动生成主键