溫馨提示×

android如何設置button顏色

小億
175
2024-08-17 12:24:40
欄目: 編程語言

要設置button的顏色,可以使用以下方法:

  1. 在xml布局文件中設置button的背景顏色:
<Button
    android:id="@+id/button"
    android:layout_width="wrap_content"
    android:layout_height="wrap_content"
    android:text="Button"
    android:background="@color/colorPrimary" />
  1. 在java代碼中設置button的背景顏色:
Button button = findViewById(R.id.button);
button.setBackgroundColor(ContextCompat.getColor(this, R.color.colorPrimary));
  1. 使用selector來設置button的不同狀態下的顏色:

在res/drawable文件夾下創建一個selector文件,比如button_selector.xml:

<selector xmlns:android="http://schemas.android.com/apk/res/android">
    <item android:state_pressed="true" android:drawable="@color/colorPrimaryDark" /> <!-- pressed -->
    <item android:state_focused="true" android:drawable="@color/colorAccent" /> <!-- focused -->
    <item android:drawable="@color/colorPrimary" /> <!-- default -->
</selector>

然后在xml布局文件中設置button的背景為該selector文件:

<Button
    android:id="@+id/button"
    android:layout_width="wrap_content"
    android:layout_height="wrap_content"
    android:text="Button"
    android:background="@drawable/button_selector" />

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