0

I want to include the below layout in a main layout file, at multiple points, but at each usage, I want to change ONLY the "android:text" attribute of the text view inside the relative layout (as seen below). How can I achieve that?

P.S. I know how to include it in the main layout. This includes the relative layout (as seen below), but the main purpose of creating another layout file is because the code (of the textview) is being repeatedly used in the main layout, and the only attribute that differs is "android:text" between these repeated text views.

<?xml version="1.0" encoding="utf-8"?>
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
    android:layout_width="match_parent"
    android:layout_height="match_parent">

    <TextView
        android:id="@+id/order_id_label"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:text="test"
        android:fontFamily="sans-serif-light"
        android:padding="20dp"
        android:textSize="20sp"
        android:textStyle="bold" />
</RelativeLayout>
TheWiz
  • 115
  • 3
  • 8

2 Answers2

5

in your another Layout file you can use this .

<include layout="@layout/main_layout"/>

And From your activity class you can set text by this.

TextView tv = (TextView) findViewById(R.id.order_id_label) tv.setText("New Text");

This is the only way you can do this .

Zahidul Islam
  • 3,180
  • 1
  • 25
  • 35
2

If all TextView element arguments are the same you could define this component in a separate file using <merge> </merge> directive and then <include layout="" /> Check here how to reuse

But if any of the TextView argument is changing, i.e. android:text attribute, the best way is to separate all other TextView attributes to custom style and reuse this custom style in different xml layout files Check here how to use styles

michal.luszczuk
  • 2,883
  • 1
  • 15
  • 22
  • I'm choosing this as the best answer because the second part(styles) is exactly what I wanted. I understood this, but can you fix the typos so other people who are looking for the same answer can understand it. Thanks – TheWiz Nov 22 '15 at 13:40