AbAppletic AbAppletic - 2 months ago 10
Android Question

android: How to make view fill available space

I couldn't really find an answer for this problem, all I did find was localized questions. Let's say I have this:

image

I can successfully do this. However, I want it that if "

BUTTON2
"'s visibility is set to
GONE
, make
BUTTON1
's width take as much as it can. So it will look like this:

image

Currently here's non-working code:

<RelativeLayout
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:layout_margin="10dp"
android:layout_gravity="center">

<com.rey.material.widget.Button
android:id="@+id/button2"
style="@style/Material.Drawable.Ripple.Wave.Light"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:onClick="goToOccasion"
android:padding="20dp"
android:text="@string/join"
app:rd_enable="true"
app:rd_rippleColor="@android:color/darker_gray"
app:rd_rippleType="wave"
android:gravity="center"
android:layout_alignParentTop="true"
android:layout_toEndOf="@+id/joinOccasionBTN"
android:layout_marginStart="87dp"
android:layout_alignBottom="@+id/joinOccasionBTN" />

<com.rey.material.widget.Button
android:id="@+id/joinOccasionBTN"
style="@style/Material.Drawable.Ripple.Wave.Light"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:onClick="goToOccasion"
android:padding="20dp"
android:text="@string/join"
app:rd_enable="true"
app:rd_rippleColor="@android:color/darker_gray"
app:rd_rippleType="wave"
android:gravity="center"
android:layout_alignParentTop="true"
android:layout_alignParentStart="true" />
</RelativeLayout>


That results in this:

image

When button2 is
visible
, and it results in the same as the pic above but without button2 ("JOIN").

Answer

An easy way to do this is using the android:layout_weight attribute in a LinearLayout.

<LinearLayout
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:orientation="horizontal"
        android:layout_margin="10dp"
        android:layout_gravity="center">

   <com.rey.material.widget.Button
       android:layout_width=0dp
       android:layout_height="wrap_content"
       android:layout_weight=1
       ...
       />

    <com.rey.material.widget.Button
       android:layout_width=0dp
       android:layout_height="wrap_content"
       android:layout_weight=1
       ...
       />

</LinearLayout>

This way, if one of your buttons changes visibility from visible to gone then the other button will fill the remaining space.

Comments