android如何设置button颜色

   2024-10-01 3680
核心提示:要设置button的颜色,可以使用以下方法:在xml布局文件中设置button的背景颜色:Buttonandroid:id=@+id/buttonandroid:layout_wi

要设置button的颜色,可以使用以下方法:

在xml布局文件中设置button的背景颜色:
<Button    android:id="@+id/button"    android:layout_width="wrap_content"    android:layout_height="wrap_content"    android:text="Button"    android:background="@color/colorPrimary" />
在java代码中设置button的背景颜色:
Button button = findViewById(R.id.button);button.setBackgroundColor(ContextCompat.getColor(this, R.color.colorPrimary));
使用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" />

 
举报打赏
 
更多>同类物流大全
推荐图文
推荐物流大全
点击排行

网站首页  |  关于我们  |  联系方式网站留言    |  赣ICP备2021007278号