Button Shape & Background Color XML - (Android Essentials: XML & Java)

<shape xmlns:android="http://schemas.android.com/apk/res/android">
    <solid android:color="@android:color/darker_gray" /> <!-- Set your desired button color here -->
    <corners android:radius="0dp" /> <!-- Set the radius to 0dp to make the corners square -->
</shape>

This XML code snippet is designed to define a drawable resource that can be used as a background for a button or any other view in your Android app. It creates a shape with a solid color and square corners, providing a simple and flat design that is commonly seen in various UI designs.

The solid element's android:color attribute sets the background color of the shape. In the provided code, it is set to use the predefined darker_gray color from the Android system resources. You can customize this color by changing the value to any color resource available in your project or defined in your colors.xml file.

The corners element with the android:radius attribute determines the roundness of the corners of the shape. A value of 0dp (density-independent pixels) ensures that the corners are square and not rounded.

How to use this code:

  1. Copy the XML code snippet.

  2. Paste it into a new XML file within the res/drawable directory of your Android project. You might name the file something like button_background.xml.

  3. To apply this drawable as a background to a button in your layout, add the android:background attribute to your button XML code with a reference to this new drawable, like so: android:background="@drawable/button_background".

  4. Customize the android:color value to match the desired color theme of your app.

Example button using this drawable:

<Button
    android:id="@+id/myButton"
    android:layout_width="wrap_content"
    android:layout_height="wrap_content"
    android:text="My Button"
    android:background="@drawable/button_background" />

This will style the button with a darker gray background and square corners. For rounded corners, change the android:radius to a positive dp value (e.g., 4dp for subtly rounded corners). Remember that the color and corner radius can be modified to fit your design specifications.