Home » Android » Reuse TextView code in Android XML

Reuse TextView code in Android XML

Posted by: admin June 15, 2020 Leave a comment

Questions:

I’m making out a few menus for my Android App and throughout there is a standard textview that is repeated 5 times, only changing the android:text tag each time, everything else is the same.

There are a good number of properties on this and it feels very inefficient to be copy/pasting all these for each of the textviews.

Is there a way I define the common properties just once and add them to each TextView element?

How to&Answers:

Yes you can define a style. Create a file in your values res folder names styles.xml and add something like this:

<resources>
    <style name="my_header_text">
        <item name="android:textStyle">bold</item>
        <item name="android:textSize">18sp</item>
        <item name="android:textColor">@android:color/white</item>
    </style>
</resources>

This defines the style. In your layout you might have a field like this:

<TextView
    android:id="@+id/my_title"
    android:layout_height="wrap_content"
    android:layout_width="wrap_content"
    style="@style/my_header_text"
    android:layout_centerVertical="true"
    android:layout_marginLeft="5dip"/>

Notice the style statement refers to the style defined above. Styles can contain almost any property. Read up on them here.