首页 > 解决方案 > Android button setBackgroundColor 改变按钮大小

问题描述

我以编程方式创建 android 按钮,并将这个按钮放在 TableRow 中,一切正常,但是当我更改背景颜色时,彩色按钮不尊重大小,因为它没有颜色:

在此处输入图像描述

我的代码是:

val btn = Button(this)
btn.isEnabled = false
btn.setBackgroundColor(Color.RED)
btn.layoutParams = TableRow.LayoutParams(150, 150)

当我不使用时setBackgroundColor,尺寸是正确的。

我不明白为什么尺寸会改变,有没有办法只改变按钮的默认灰色,而不改变尺寸。

标签: androidkotlinbutton

解决方案


按钮的默认背景不是纯色,而是具有内置填充和边距的图形(例如九块位图)。因此,当您用颜色替换该背景图像时,所有内置的填充和边距都会被丢弃。

与其设置背景颜色,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>

这产生了这个渲染: 水平布局的红色按钮和默认按钮


推荐阅读