Home » Android » Reuse TextView code in Android XML

Reuse TextView code in Android XML

Posted by: admin June 15, 2020 Leave a comment


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:

    <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>

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


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