android怎么改变button的背景颜色

要改变Android中Button的背景颜色,可以使用如下方法:

在XML布局文件中设置Button的背景颜色:

<Button
    android:id="@+id/myButton"
    android:layout_width="wrap_content"
    android:layout_height="wrap_content"
    android:text="Click Me"
    android:background="@color/colorPrimary" />

在这个例子中,@color/colorPrimary是一个颜色资源,你可以在res/values/colors.xml文件中定义它。

在Java代码中设置Button的背景颜色:

Button myButton = findViewById(R.id.myButton);
myButton.setBackgroundColor(getResources().getColor(R.color.colorPrimary));

使用Selector设置Button的不同状态下的背景颜色:
res/drawable目录下创建一个button_selector.xml文件:

<selector xmlns:android="http://schemas.android.com/apk/res/android">
    <item android:state_pressed="true" android:drawable="@color/colorPrimaryDark" />
    <item android:drawable="@color/colorPrimary" />
</selector>

然后在Button的XML布局文件中设置背景:

<Button
    android:id="@+id/myButton"
    android:layout_width="wrap_content"
    android:layout_height="wrap_content"
    android:text="Click Me"
    android:background="@drawable/button_selector" />
阅读剩余
THE END