学堂 学堂 学堂公众号手机端

要设置Android按钮的颜色,可以使用以下方法: 在XML布局文件中设置按钮的背景颜色: <Button android:id="@+id/button"

lewis 2年前 (2023-12-26) 阅读数 6 #技术

要设置Android按钮的颜色,可以使用以下方法:

  1. 在XML布局文件中设置按钮的背景颜色:
<Button android:id="@+id/button" android:layout_width="wrap_content" android:layout_height="wrap_content" android:text="Button" android:background="@color/colorPrimary"/>
  • 在java代码中设置按钮的背景颜色:
  • Buttonbutton=findViewById(R.id.button); button.setBackgroundColor(getResources().getColor(R.color.colorPrimary));
  • 使用Selector设置按钮的不同状态下的颜色: 在res/drawable文件夹下创建一个selector文件,例如button_selector.xml,内容如下:
  • <selectorxmlns:android="http://schemas.android.com/apk/res/android"> <itemandroid:state_pressed="true"android:drawable="@color/colorAccent"/> <itemandroid:drawable="@color/colorPrimary"/> </selector>

    然后在布局文件或java代码中设置按钮的背景为这个selector:

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

    通过以上方法可以设置Android按钮的颜色。


    版权声明

    本文仅代表作者观点,不代表博信信息网立场。

    热门