Kunal Das
Kunal Das

Reputation: 25

Keep common/redundant xml attributes in separate file for reuse

I have to keep adding these attributes for padding over and over again in almost every element

<TextView
android:paddingLeft="@dimen/padding"
android:paddingRight="@dimen/padding"
android:paddingTop="@dimen/less_padding"
android:paddingBottom="@dimen/less_padding">

What I want is to put these 4 lines in a separate file and then use that file as a single line of code to apply whenever I want in any element. Is it possible?

Upvotes: 0

Views: 63

Answers (1)

Ben P.
Ben P.

Reputation: 54244

Create a file styles.xml in your res/values/ directory, and put this in it:

<resources xmlns:android="http://schemas.android.com/apk/res/android">

    <style name="CommonPadding">
        <item name="android:paddingLeft">@dimen/padding</item>
        <item name="android:paddingRight">@dimen/padding</item>
        <item name="android:paddingTop">@dimen/less_padding</item>
        <item name="android:paddingBottom">@dimen/less_padding</item>
    </style>

</resources>

Then, in your various layout files, you can do this:

<TextView
    style="@style/CommonPadding"
    ...
    />

Upvotes: 2

Related Questions