要改变Android中Button的背景颜色,可以使用如下方法:
- 在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
文件中定义它。
ButtonmyButton=findViewById(R.id.myButton);
myButton.setBackgroundColor(getResources().getColor(R.color.colorPrimary));
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"/>