Search code examples
androidandroid-linearlayout

How to make element of LinearLayout not fill all possible space with weight=1 width=0


I have next layout:

 <LinearLayout
            android:id="@+id/work_item_layout"
            android:orientation="horizontal"
            android:layout_width="match_parent"
            android:gravity="left"
            android:background="@android:drawable/list_selector_background"
            android:layout_height="wrap_content">
        <TextView
                android:layout_width="wrap_content"
                android:layout_height="wrap_content"
                 android:textSize="6sp"
                android:id="@+id/work_item_update"/>
        <TextView
                android:layout_width="0dp"
                android:layout_weight="1"
                android:layout_height="wrap_content"
                android:textSize="16sp"
                android:maxLines="2"
                android:text="LALALALLALLALALALALALALLA...."
                android:id="@+id/work_item_title">
        <TextView
                android:layout_width="wrap_content"
                android:layout_height="wrap_content"
                android:maxLines="1"
                android:textSize="13sp"
                android:id="@+id/work_item_rate_and_size"/>

    </LinearLayout>

Problem is central TextView fill all available space but i want it to be minimum possible space. If i make width of central TextView "warp_content" then last one will be erased if central would big enough to fill all space. How should i make central element width be like warp_content but last one must not be erased if central text is more then 1 line (i want that last one TextView text will be right next to central TextView text)


Solution

  • I think you are using weights exactly backwards. Try assigning android:weight="1" for the top and bottom TextViews and specifying only "wrap_content" for the middle one.

    Alternatively, you could specify large weights (4 or 5) to each of the outside views and a smaller weight (1) for the inside one.

    Weight takes precedence. If you specify a weight for a view, the LinearLayout will use it, in preference to other size specifications, to size the view. If you specify both weight and some other size, the LinearLayout size computation is excessively expensive. That is why you will see a recommendation, in your IDE, telling you to explicitly set the size to "0", if you specify a weight.

    Specifying a non-zero weight can be useful. While weight takes precedence if there is space to spare, the LinearLayout size calculation algorithm will not make a view smaller that its specified size. That means that you can say, more or less "give this view 1/3rd of the screen, or 12 pixels, whichever is larger"