SAIR SAIR - 9 days ago 6
Android Question

Android: creating dynamic layout

I want to create a dynamic horizontal layout which have 3 views which take equal space on screen. When 1 view is hidden then remaining views should fill up its space.

I am trying to achieve this using xml and not considering to write some code for it.

I am able to get 3 views to take equal space to fill the screen by using

LinearLayout
and weight but not able make it so that view should fill the space if some views are hidden.

My layout looks like this.

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

<TextView
android:layout_width="0dp"
android:layout_weight="1"
android:layout_height="wrap_content"
android:text="This is bob" />
<TextView
android:layout_width="0dp"
android:layout_weight="1"
android:layout_height="wrap_content"
android:text="This is bob" />
<TextView
android:layout_width="0dp"
android:layout_weight="1"
android:layout_height="wrap_content"
android:text="This is bob" />
</LinearLayout>


I thought it must be already asked by someone but i am not able to find any relevant question.

Answer

Add

android:orientation="horizontal" 

and remove

android:weightSum="3" 

from main layout it will work.

Your layout should be like this:

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

    <TextView
        android:layout_width="0dp"
        android:layout_weight="1"
        android:layout_height="wrap_content"
        android:text="This is bob" />
    <TextView
        android:layout_width="0dp"
        android:layout_weight="1"
        android:layout_height="wrap_content"
        android:text="This is bob" />
    <TextView
        android:layout_width="0dp"
        android:layout_weight="1"
        android:layout_height="wrap_content"
        android:text="This is bob" />
</LinearLayout>
Comments