android

android如何设置button颜色

小亿
98
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
看了该问题的人还看了