android – How to reuse layouts/layout-attributes and change single attributes afterwards-ThrowExceptions

Exception or error:

I have this simple button XML:

<layer-list xmlns:android="http://schemas.android.com/apk/res/android">
<item>
    <shape  android:shape="rectangle">
        <solid android:color="@color/some_color" />
    </shape>
</item>

And I use it like so:

<Button
    android:textColor="#ffffff"
    android:background="@drawable/buttonxml"
    android:layout_width="wrap_content"
    android:layout_height="wrap_content"
    android:text="String"
    android:id="@+id/button"/>

Problem is, by doing so the only color I can have with this button XML is some_color. If I want to reuse this same layout, I’ll need to create another XML to just change the color. Is there somehow I can reuse the button XML, changing only some values? I was thinking in something like:

<Button
    android:textColor="#ffffff"
    android:background="@drawable/buttonxml"
    android:layout_width="wrap_content"
    android:layout_height="wrap_content"
    android:text="String"
    android:id="@+id/button"
    parent:color="@color/anotherColor"/>
How to solve:

You could create a Custom Button style in your styles.xml to reuse specific styles:

<style name="CustomButtonStyle" parent="@android:style/Widget.Button">
    <item name="android:background">@drawable/buttonxml</item>
    <item name="android:textColor">#ffffff</item>
</style>

You can use this style in you layouts:

<Button
    android:layout_width="wrap_content"
    android:layout_height="wrap_content"
    android:text="String"
    android:id="@+id/button"
    style="@style/CustomButtonStyle"  
    />

The textColor will be white and the the background will be buttonxml.


If you want to overwrite singe attributes just add it to yout layout. They will overwrite the style (the Theme style and the style in the layout)

<Button
    android:id="@+id/button"
    android:layout_width="wrap_content"
    android:layout_height="wrap_content"
    android:text="String"
    style="@style/CustomButtonStyle"  
    android:textColor="@color/anotherColor"


    />

Here the textcolor will be anotherColor but the background will still be buttonxml.

Alternative

Use include to reuse a whole layout. You can also overwrite attributes if you add them in the include.

<include android:id=”@+id/news_title”
     android:layout_width="wrap_content"
     android:layout_height="wrap_content"
     android:textColor="@color/anotherColor"
     layout=”@layout/yourbuttonlayout”/>

Leave a Reply

Your email address will not be published. Required fields are marked *