Change Android Button Background Color
To change the background color of a Button in Android, you can use the following method:
- Set the background color of a Button in an XML layout file.
<Button
android:id="@+id/myButton"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="Click Me"
android:background="@color/colorPrimary" />
In this example, @color/colorPrimary is a color resource that you can define in the res/values/colors.xml file.
- Set the background color of a Button in Java code.
Button myButton = findViewById(R.id.myButton);
myButton.setBackgroundColor(getResources().getColor(R.color.colorPrimary));
- resources for drawing
- XML file for selecting buttons
<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>
Then set the background in the XML layout file for the Button.
<Button
android:id="@+id/myButton"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="Click Me"
android:background="@drawable/button_selector" />