How to add two Buttons next to each other? (Button

2019-08-31 08:25发布

问题:

I want two buttons next to each other like this: [ Use ] [ Cancel ] (These are just buttons with background images, NOT ImageButtons)

But the result is strange, the first button fills all the space, in the linear layout like this: [..........Use...........] and the Cancel button is not shown. The layout_width are "wrap_content" for both buttons, and the linear layout's orientation is horizontal whats the problem?

Got a code:

 <LinearLayout 
   android:layout_width="fill_parent"
   android:orientation="horizontal"
   android:id="@+id/linearLayout2" 
   android:layout_gravity="bottom" 
   android:layout_height="fill_parent" 
   android:layout_weight="1">


       <Button 
       android:text="Use" 
       android:height="14dp"
       android:textSize="15sp"
       android:textColor="#ffffff"
       android:background="@drawable/button1"
       android:layout_width="wrap_content" 
       android:layout_height="wrap_content" 
       android:id="@+id/UseButtonDialog" 
       android:layout_gravity="bottom">
       </Button>


        <Button android:text="Cancel" 
        android:background="@drawable/button1"
        android:height="14dp"
        android:textSize="15sp"
        android:textColor="#ffffff"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content" 
        android:id="@+id/CancelButtonDialog" 
        android:layout_gravity="bottom">
        </Button>


   </LinearLayout>

Something should i do with the images?

回答1:

add layout_weight attribute to both the buttons. set it to 1.

or maybe removing layout_weight from the linear layout works as well.



回答2:

Use this:

Give weight=1 for each component (or give weightsum=1 for LinearLayout & weights 0.5 to Buttons)

<LinearLayout android:layout_width="fill_parent"
   android:orientation="horizontal"
   android:id="@+id/linearLayout2" 
   android:layout_gravity="bottom" 
   android:layout_height="fill_parent">
       <Button android:weight="1"
       android:text="Use" 
       android:height="14dp"
       android:textSize="15sp"
       android:textColor="#ffffff"
       android:background="@drawable/button1"
       android:layout_width="wrap_content" 
       android:layout_height="wrap_content" 
       android:id="@+id/UseButtonDialog" 
       android:layout_gravity="bottom">
       </Button>
        <Button android:weight="1"
        android:text="Cancel" 
        android:background="@drawable/button1"
        android:height="14dp"
        android:textSize="15sp"
        android:textColor="#ffffff"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content" 
        android:id="@+id/CancelButtonDialog" 
        android:layout_gravity="bottom">
        </Button>
</LinearLayout>