0

I want to make 3 similar buttons, the difference between them is that they are different colors. I had found out earlier that the way to give the buttons rounded corners is through creating an xml file for it, but in that case I had added the color for the button into the xml file. In this case I don't want to do that, since then I would have to make 3 virtually identical xml files to change the color for each button. Is there a way to split the code to have all three buttons reference a single xml for the button style, and have a separate line of code to just modify the color?

Doragon
  • 199
  • 1
  • 10

1 Answers1

1

Within the values folder of your project, create a styles.xml file (if it doesn't already exist). Then, add code similar to below to set the common features that you want each button to have:

<!-- Style for a button -->
<style name="buttonStyle">
    <item name="android:layout_height">wrap_content</item>
    <item name="android:layout_width">wrap_content</item>
    <item name="android:fontFamily">sans-serif</item>
    <item name="android:textAllCaps">false</item>
</style>

Then, in your layout file, reference this style that you just created in all three of your buttons similar to the following:

    <Button
        android:id="@+id/restore_button"
        style="@style/buttonStyle"
        android:layout_width="200dp"
        android:textSize="18sp"
        android:layout_height="wrap_content"
        android:text="@string/restore_button_text" />

Then, change the color of each button individually with the following code in each button layout:

android:background="@android:color/white"

Finally, if you want to also create a button with rounded corners, reference this StackOverflow post for directions: How to make the corners of a button round? You will need to create a custom layout and reference it within each button as a Drawable.

shagberg
  • 2,427
  • 1
  • 12
  • 23
  • Is there a way to split the color and rounded corners? In your answer you had color as a background, and in the post you referenced also had rounded corners as a background, and I thought you can’t have 2 backgrounds. I’d rather not make three different xml just to change the color. – Doragon May 09 '21 at 06:03
  • Take a look at Sandip Jadhav’s answer on that same link. It appears that a simpler way to create rounded corners would be to add this to your button layout: android:radius="10dp". – shagberg May 09 '21 at 13:00