Search code examples
javaandroidtextviewandroid-xmlandroid-wrap-content

Why does textview with weight have invalid height in case of text wrapping?


I have a dialog, which has a layout xml. Controls are vertically aligned, and in one "row" there is a textview and a seekbar. Textview has weight=1, and seekbar has weight=2.

Now the problem is that if textview cannot fit, it is wrapped, but the height of the textview is not adjusted, and the second line is not visible.

Layout xml:

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

  <LinearLayout 
    android:id="@+id/dialog_settings_layout_main"
    android:layout_width="wrap_content"
    android:layout_height="wrap_content"
    android:minWidth="240dp"
    android:padding="10dp"
    android:orientation="vertical" >

    ....other controls.....

    <LinearLayout 
    android:id="@+id/dialog_settings_layout_volume"
    android:layout_width="match_parent"
    android:layout_height="wrap_content"
    android:orientation="horizontal" >

    <TextView
        android:id="@+id/textView_dialog_settings"
        android:layout_width="0px"
        android:layout_height="wrap_content"
        android:layout_weight="1"
        android:text="aaaaaaaaa bbbbbbbbbb cccccccccc"
        android:layout_gravity="center_vertical"
        android:paddingRight="20dp"
        android:textAppearance="?android:attr/textAppearanceMedium" />

    <SeekBar
        android:id="@+id/seekbar_dialog_settings"
        android:layout_width="0px"
        android:layout_weight="2"
        android:layout_height="wrap_content"
        android:layout_gravity="center_vertical"
        android:max="8"
        android:progress="1" />

    </LinearLayout>

    ....other controls.....


Solution

  • OK, I think I have solution.

    Set match_parent for ScrollView width and height and horizontal LinearLayout width.

    <ScrollView xmlns:android="http://schemas.android.com/apk/res/android"
    android:layout_width="match_parent"
    android:layout_height="match_parent" >
    
      <LinearLayout 
        android:id="@+id/dialog_settings_layout_main"
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:minWidth="240dp"
        android:padding="10dp"
        android:orientation="vertical" >
    

    I have tried to reproduce it and everything worked till I wrapped layout with ScrollView which I missed at the beginning. Then I had exactly the same problem, adjusting mentioned values solved it.

    Update

    To make it work inside Dialog, create one using AlertDialog.Builder

    AlertDialog.Builder builder = new AlertDialog.Builder(this);
    View view = getLayoutInflater().inflate(R.layout.dialog_layout, null);
    builder.setView(view);
    AlertDialog dialog = builder.create();
    
    dialog.show();