how to set textview width wrap_content but limit to 1/3 of parent's width

lannyf picture lannyf · May 4, 2015 · Viewed 9.7k times · Source

Having a TextView, its width should not go over 1/3 of its parent's width. If its width is smaller than 1/3 of parent, it should have wrap_content behavior. Its horizontal sibling will always start next to it.

Tried following, it always has hard cut of 1/3 and 2/3, so if the text1 has less space than 1/3 the TextView two will not start next to it.

change the LinearLayout to RelativeLayout, then the android:layout_weight="n" does not work

basically, need to define width is wrap_content and the maxWidth does not go over 1/3.

any suggestion?

<LinearLayout 
    android:layout_width="match_parent"
    android:layout_height="wrap_content"
    android:orientation="horizontal"
    android:weightSum="3">

    <TextView 
        android:layout_width="0dp"
        android:layout_height="wrap_content"
        android:layout_weight="1"
        android:singleLine="true"
        android:ellipsize="end"
    />

    <TextView 
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:layout_width="0dp"
        android:singleLine="true"
        android:ellipsize="end"
        android:layout_weight="2"
    />
</LinearLayout>

Answer

user3829751 picture user3829751 · May 4, 2015

basically, need to define width is wrap_content and the maxWidth does not go over 1/3.

If that's all you need, then my suggestion is to scrap the Weight approach and dynamically set the TextView's maxWidth value.

Something like this:

tv.setMaxWidth(((LinearLayout)tv.getParent()).getWidth()/3);