Reputation: 437
Use Case:
I have a Horizontal view H, which contains 5 buttons(A,B,C,D & E); all taking equal space in H. Now depending on certain business logic each of these buttons may or may not be visible. In case a button is invisible, rest of the buttons should align themselves equally.
Now the problem is if I give specific weights to each of these buttons then I have to write 2^5 if-else cases to assign individual weights to buttons. Isn't there a way in Android that all these buttons align them self taking equal space on their own. Precisely the idea is to write just 5 cases where I make a button visible or invisible and rest view align itself on its own. I can not use wrap content as these buttons contain text of different length and I want the buttons to take equal space and not the text.
Is there a way of doing this? I'll highly appreciate any help here.
Upvotes: 1
Views: 600
Reputation: 10204
Assign all your buttons equal weight (e.g. 1), but don't assign weight sum to the container. Now, when you need to hide a button, set its visibility to GONE
, and other buttons will be resized equally to take available space.
Upvotes: 3
Reputation: 327
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="fill_parent"
android:layout_height="fill_parent"
android:background="@color/white"
android:orientation="vertical" >
<Button
android:layout_width="fill_parent"
android:layout_weight="1" />
<Button
android:layout_width="fill_parent"
android:layout_weight="1" />
<Button
android:layout_width="fill_parent"
android:layout_weight="1"
android:visibility="gone" />
</LinearLayout>
Now if you set the third button visible the other two buttos will resize to show 3 buttons on screen. And the same view in horizontal layout:
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="fill_parent"
android:layout_height="fill_parent"
android:background="@color/white"
android:orientation="horizontal" >
<Button
android:layout_height="fill_parent"
android:layout_weight="1" />
<Button
android:layout_height="fill_parent"
android:layout_weight="1" />
<Button
android:layout_height="fill_parent"
android:layout_weight="1"
android:visibility="gone" />
</LinearLayout>
Upvotes: 0