要改变Android中Button的背景颜色,可以使用如下方法:
<Button android:id="@+id/myButton" android:layout_width="wrap_content" android:layout_height="wrap_content" android:text="Click Me" android:background="@color/colorPrimary" /> 在这个例子中,@color/colorPrimary是一个颜色资源,你可以在res/values/colors.xml文件中定义它。
Button myButton = findViewById(R.id.myButton); myButton.setBackgroundColor(getResources().getColor(R.color.colorPrimary)); res/drawable目录下创建一个button_selector.xml文件:<selector xmlns:android="http://schemas.android.com/apk/res/android"> <item android:state_pressed="true" android:drawable="@color/colorPrimaryDark" /> <item android:drawable="@color/colorPrimary" /> </selector> 然后在Button的XML布局文件中设置背景:
<Button android:id="@+id/myButton" android:layout_width="wrap_content" android:layout_height="wrap_content" android:text="Click Me" android:background="@drawable/button_selector" />