Android Button Color: Complete Guide
To set the color for Android buttons, you can use the following method:
- Set the background color of the button in the XML layout file:
<Button
android:id="@+id/button"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="Button"
android:background="@color/colorPrimary" />
- Set the background color of a button in Java code.
Button button = findViewById(R.id.button);
button.setBackgroundColor(getResources().getColor(R.color.colorPrimary));
- Use Selector to set the colors of buttons in different states:
Create a selector file in the res/drawable folder, for example button_selector.xml, with the following content:
<selector xmlns:android="http://schemas.android.com/apk/res/android">
<item android:state_pressed="true" android:drawable="@color/colorAccent" />
<item android:drawable="@color/colorPrimary" />
</selector>
Next, set the background of the button to this selector in the layout file or Java code.
<Button
android:id="@+id/button"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="Button"
android:background="@drawable/button_selector" />
You can change the color of an Android button using the above method.