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

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

lewis 1年前 (2024-02-10) 阅读数 4 #技术

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

  1. 在XML布局文件中设置Button的背景颜色:
<Button android:id="@+id/myButton" android:layout_width="wrap_content" android:layout_height="wrap_content" android:text="ClickMe" android:background="@color/colorPrimary"/>

在这个例子中,@color/colorPrimary是一个颜色资源,你可以在res/values/colors.xml文件中定义它。

  • 在Java代码中设置Button的背景颜色:
  • ButtonmyButton=findViewById(R.id.myButton); myButton.setBackgroundColor(getResources().getColor(R.color.colorPrimary));
  • 使用Selector设置Button的不同状态下的背景颜色: 在res/drawable目录下创建一个button_selector.xml文件:
  • <selectorxmlns:android="http://schemas.android.com/apk/res/android"> <itemandroid:state_pressed="true"android:drawable="@color/colorPrimaryDark"/> <itemandroid:drawable="@color/colorPrimary"/> </selector>

    然后在Button的XML布局文件中设置背景:


    <Button android:id="@+id/myButton" android:layout_width="wrap_content" android:layout_height="wrap_content" android:text="ClickMe" android:background="@drawable/button_selector"/>
    版权声明

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

    热门