溫馨提示×

android怎么改變button的背景顏色

小億
266
2024-02-22 16:59:32
欄目: 編程語言

要改變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" />

0
亚洲午夜精品一区二区_中文无码日韩欧免_久久香蕉精品视频_欧美主播一区二区三区美女