Rajkiran
Rajkiran

Reputation: 16193

Buttons in LinearLayout issue

I have a custom dialog which has 3 buttons and sometimes it has one button only. When I have 3 buttons, the LinearLayout fits those buttons well in itself. But when I have just one button, it gives the whole width available to a single button making that button look too big. I want that, if there's only one button, it should only take half the the complete width available or should wrap content (Button image.) See following images for reference-

3 buttons dialog

1 button dialog

Upvotes: 1

Views: 294

Answers (2)

Renard
Renard

Reputation: 6929

In order to have one button take up half the available screen width you need to

  1. set android:weightSum="2" in the parent LinearLayout
  2. set android:layout_weight="1" in the Button

Upvotes: 1

Shankar Agarwal
Shankar Agarwal

Reputation: 34765

Refer this XML file which is similar to your requirement. Just visibility to gone to not required button.

<?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:orientation="horizontal" android:weightSum="3" android:gravity="center_horizontal">

    <Button
        android:id="@+id/button1"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:layout_weight="1"
        android:text="Button"/>


    <Button
        android:id="@+id/button2"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:layout_weight="1"
        android:text="Button" />

    <Button
        android:id="@+id/button3"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:layout_weight="1"
        android:text="Button"/>

</LinearLayout>

Upvotes: 3

Related Questions