skip to Main Content

i will repeat 10 of the following code but i ask for How do I shorten the following code ?
Is there a short way to repeat this code without typing it all ?

   <TextView
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:layout_marginTop="24dp"
        android:text=" view 1 "
        android:textAlignment="center"
        android:textColor="@color/black"
        android:textSize="36dp" />

2

Answers


  1. Define a style containing all the common attributes and set style in textview . In your case style may contain , textAlignment , textColor , textSize and if you want layout_width and layout_width also . If you want to change value for only one textview , you can always override that parameter in xml file.

      <style name="TextCommanStyle">
            <item name="android:layout_width">match_parent</item>
            <item name="android:layout_height">wrap_content</item>
            <item name="android:textColor">@color/black</item>
            <item name="android:textSize">20sp</item>
        </style>
    

    your xml file.

       <TextView
            android:id="@+id/titleTextView"
            style="@style/TextCommanStyle"
            tools:text="Text 1" />
    
        <TextView
            android:id="@+id/descTextView"
            style="@style/TextCommanStyle"
            android:layout_marginTop="10dp"
            tools:text="Text 2" />
    
    
        <TextView
            android:id="@+id/desc2TextView"
            style="@style/TextCommanStyle"
            android:layout_marginTop="10dp"
            android:textColor="@color/teal_200"  // override color if you want
            tools:text="Text 3" />
    

    In case you want to change textColor or add new attribute to each textview, add to a commom style and it will reflect on all view using that style.
    You can create multiple styles depending upon your use case

    Login or Signup to reply.
  2. Use an include to reused a layout without duplicating it:

    https://developer.android.com/training/improving-layouts/reusing-layouts

    Login or Signup to reply.
Please signup or login to give your own answer.
Back To Top
Search