我以编程的方式创建了android按钮,我把这个butons放在一个TableRow里,所有的事情都很好,但是当我改变backgroudColor的时候,彩色按钮并不像没有颜色的按钮那样尊重大小。
我的代码是:
val btn = Button(this)
btn.isEnabled = false
btn.setBackgroundColor(Color.RED)
btn.layoutParams = TableRow.LayoutParams(150, 150)
当我不使用 setBackgroundColor
大小是正确的。
我不明白为什么要改变大小,有什么办法可以只改变按钮的默认灰色,而不改变大小。
一个按钮的默认背景不是纯色的,而是一个图形(例如一个 九宫格位图),它有内置的paddings和margin。因此,当你用颜色替换该背景图像时,所有内置的填充和边距都会被丢弃。
而不是用 setBackgroundColor()
你可以尝试使用 setBackgroundTintList()
它应该用你选择的颜色来着色现有的背景图片。
或者,你需要在将背景改为纯红色后手动设置页边距和页脚,这比在布局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>
如果你的 app theme
是 material-theme
然后,有一个默认的paddings应用到按钮,这就是为什么你应用它后,颜色填满了整个按钮的画布。