Home > Software engineering >  Align TextViews in specific way
Align TextViews in specific way

Time:09-17

I am currently learning some techniques in Android and I would like to add TextViews via button press (via Java) into the app (View). But before they get added through code I want to attach to each TextView a self made preconfigurartion style from "res/values/styles.xml". That is the main idea so far.

Basically I would like to know how to configure my TextViews (in styles.xml) and the given Layout (e.g. main_activity.xml) in the XML file of an Activity in such a way so they look like in this picture:

Like so

So the goal is to preconfigure the Layout and TextView in such a way, that I only have to add the TextViews one after another so that they align themselfes in the way like in the picture.

What do I have to do exactly in order to achieve this?

// main_activity.xml

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

    <RelativeLayout
        android:layout_width="match_parent"
        android:layout_height="wrap_content">

        <TextView style="@style/AddedTextView" />

    </RelativeLayout>
    
    ...

    <Button
        android:id="@ id/btn_add"
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:text="Button" />
</LinearLayout>

// res/values/styles.xml

<?xml version="1.0" encoding="utf-8"?>
<resources>
    <style name="AddedTextView" parent="Widget.AppCompat.TextView">
        <item name="android:layout_width">wrap_content</item>
        <item name="android:layout_height">wrap_content</item>
        <item name="android:background">@drawable/custom_textview_design</item>
        <item name="android:text">TestTV</item>
        <item name="android:textColor">@color/common_text_color</item>
        <item name="android:textSize">7pt</item>
        <item name="android:layout_alignParentLeft">true</item>
    </style>
</resources>

CodePudding user response:

You can apply the style programmatically using a ContextThemeWrapper:

val textView = TextView(ContextThemeWrapper(this, R.style.AddedTextView))

And to add TextViews connected to one another and wrap them vertically, you can use the Google's enter image description here

  • Related