温馨提示×

android怎么改变button的背景颜色

小亿
253
2024-02-22 16:59:32
栏目: 编程语言
Android开发者专用服务器限时活动,0元免费领,库存有限,领完即止! 点击查看>>

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

  1. 在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文件中定义它。

  1. 在Java代码中设置Button的背景颜色:
Button myButton = findViewById(R.id.myButton);
myButton.setBackgroundColor(getResources().getColor(R.color.colorPrimary));
  1. 使用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" />

亿速云「云服务器」,即开即用、新一代英特尔至强铂金CPU、三副本存储NVMe SSD云盘,价格低至29元/月。点击查看>>

推荐阅读:c语言怎么改变背景的颜色

0