简体   繁体   中英

TextView text alignment to center

I want to align text inside TextView to the center. I used android:gravity="center" but it leaves extra spacing between words.

<LinearLayout
        android:id="@+id/textContainer"
        android:orientation="vertical"
        android:layout_weight="4"
        android:layout_width="match_parent"
        android:layout_height="wrap_content">

        <TextView
            android:id="@+id/title"
            android:layout_width="match_parent"
            android:layout_height="wrap_content"
            android:layout_marginTop="16dp"
            android:layout_marginBottom="16dp"
            android:textSize="24sp"
            android:textStyle="bold"
            android:textColor="@color/colorTextDarkGrey"
            android:gravity="center"
            android:text="INTRO TITLE"/>

        <TextView
            android:id="@+id/text"
            android:layout_width="match_parent"
            android:layout_height="wrap_content"
            android:textSize="14sp"
            android:textStyle="normal"
            android:textColor="@color/colorTextLightGrey"
            android:gravity="center"
            android:text="Lorem ipsum dolor sit amet, consectetur adipiscing elit, sed do eiusmod tempor incididunt ut
            labore et dolore magna aliqua."/>

    </LinearLayout>

Expected result:

在此输入图像描述

The reason why you see spacing between words is the extra line you are using for the text, which is introducing spaces between incididunt ut and labore et .

Just replace this (two lines):

android:text="Lorem ipsum dolor sit amet, consectetur adipiscing elit, sed do eiusmod tempor incididunt ut
            labore et dolore magna aliqua."

With this (one line):

android:text="Lorem ipsum dolor sit amet, consectetur adipiscing elit, sed do eiusmod tempor incididunt ut labore et dolore magna aliqua."

I hope it helps!

If the text of the TextView has to be fixed then just eliminate any new line breaks, otherwise if you want to do this programmatically you can just make sure you won't pass a string with line breaks:

TextView text = findViewById(R.id.text);
String sampleString = "Line 1\nLine 2";
text.setText(sampleString.replace("\n", " "));

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM