SAIR
SAIR

Reputation: 1141

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.

Upvotes: 0

Views: 83

Answers (2)

Ready Android
Ready Android

Reputation: 3632

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>

Upvotes: 2

Alex Shutov
Alex Shutov

Reputation: 3282

Use databinding for changing android:weightSum attribute in container when view's visibility is set to GONE. see docs: https://developer.android.com/topic/libraries/data-binding/index.html. You'll have to create one model object anyways.

Upvotes: 0

Related Questions