Home > Mobile >  Android TextView multiline has extra space
Android TextView multiline has extra space

Time:10-17

Multiline TextViews with android:layout_width="wrap_content" automatically take up maximum space as if they become match_parent. Is there any way keep the true wrap_content behavior?

Example xml:

<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:tools="http://schemas.android.com/tools"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    android:gravity="center_horizontal"
    android:orientation="vertical"
    tools:context=".MainActivity">

    <TextView
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:background="@drawable/rounded_bg"
        android:backgroundTint="@color/colorAccent"
        android:text="Example text"
        android:textAlignment="center"
        android:textColor="#fff"
        android:textSize="28sp" />

    <TextView
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:layout_marginTop="10dp"
        android:background="@drawable/rounded_bg"
        android:backgroundTint="@color/colorAccent"
        android:text="Example text ================"
        android:textAlignment="center"
        android:textColor="#fff"
        android:textSize="28sp" />

    <TextView
        android:layout_width="270dp"
        android:layout_height="wrap_content"
        android:layout_marginTop="10dp"
        android:background="@drawable/rounded_bg"
        android:backgroundTint="@color/colorAccent"
        android:text="Example text ================"
        android:textAlignment="center"
        android:textColor="#fff"
        android:textSize="28sp" />

</LinearLayout>

enter image description here

  1. Single line
  2. Multiline
  3. How I want it to look

I want to remove the extra space at the left and right ends of the multiline text. The effect can be done if I manually set the layout_width to some specific value like 270dp, but then it becomes arbitrary. I prefer to keep it as wrap_content.

EDIT: The purpose of this is that I want to use a custom background, rounded bg that fits onto the text. I've edited the example xml and the images.

CodePudding user response:

Put this line of code in the textview and test again,

android:inputType="textMultiLine"

also remove gravity center and use textAlignment center, maybe it will work

CodePudding user response:

Try it programmatically in .java file without changing xml file

SpannableString s = new SpannableString("your content");             
s.setSpan(new BackgroundColorSpan(getResources().getColor(R.color.colorAccent)), 0, s.length(), Spanned.SPAN_INCLUSIVE_INCLUSIVE);                     
text.setText(s);
  • Related