Question

I am using GridLayout from the support Library. Some of the cells contain player information - I use a Linear Layout with two TextViews. I have not been able to get the name (the second text view) to wrap.

Current behavior:

123
John Cochtousczyon

Desired behavior:

123
John
Cochtousczyon

Here's the current state of the cell layout xml:

<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:orientation="vertical" >

<TextView
    android:id="@+id/player_id"
    android:layout_width="fill_parent"
    android:layout_height="wrap_content"
    android:gravity="left"
    android:text="test" />

<TextView
    android:id="@+id/player_name"
    android:layout_width="fill_parent"
    android:layout_height="wrap_content"
    android:ellipsize="end"
    android:minLines="2"
    android:scrollHorizontally="false"
    android:text="testing thisout with extra sauce"
    android:textSize="18sp" />

</LinearLayout>

and the code that adds him to the grid:

    lp = (GridLayout.LayoutParams) playerCell.getLayoutParams();
    lp.columnSpec = GridLayout.spec(nameCol);
    lp.rowSpec = GridLayout.spec(nameRow);
    playerGrid.addView(playerCell, lp);

Ideally I would like a solution that sets the column width for the widest cell AFTER wrapping the name. I've gotten close to the desired result using maxEms, but that requires balancing the most likely needed limit against how much truncation to tolerate with longer names.

P'r'aps there's nothing for it but to fix the width - just thought I'd ask in case all the smarter people than me out there have solved this.

Was it helpful?

Solution

Here's what I've settled on for now, until something better comes along:

<TextView
    android:id="@+id/player_name"
    android:layout_width="fill_parent"
    android:layout_height="wrap_content"
    android:ellipsize="end"
    android:maxEms="4"
    android:maxLines="2"
    android:text="testing thisout with extra sauce"
    android:textSize="18sp" />

combination of fill_parent, ellipsize END, maxEms and maxLines gets me close enough.

OTHER TIPS

If anyone is still looking this in 2020 Android now has a inbuilt way of doing this. Just add this code to your java file

TextviewCompat.setAutoSizeTypeWithDefaults(<your textview refernce here>, TextviewCompat.AUTO_SIZE_TEXT_TYPE_UNIFORM);

Also make sure you add this to your textview xml

android:ellipsize="none"

Hopefully this will help someone; I simply used the good old "\n" to wrap.

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top