Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Reuse TextView code in Android XML

Tags:

android

xml

menu

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?

like image 282
Mark D Avatar asked Nov 06 '10 00:11

Mark D


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

like image 51
dhaag23 Avatar answered Oct 13 '22 01:10

dhaag23