Center a button in a Linear layout

Center a button in a Linear layout

Asked on December 17, 2018 in XML.
Add Comment


  • 3 Answer(s)

    Simple way to center a button in layout:

         To center an item in the middle of the screen no need to use a LinearLayout as these are to  display a number of items in a row.Use RelativeLayout for that.

    android:layout_gravity="center_vertical|center_horizontal"
    

    for accordant RelativeLayout option:

    android:layout_centerInParent="true"
    

    The layout file will look like below,

    <?xml version="1.0" encoding="utf-8"?>
    <RelativeLayout android:id="@+id/RelativeLayout01"
      android:layout_width="fill_parent"
      android:layout_height="fill_parent"
      xmlns:android="http://schemas.android.com/apk/res/android">
     
      <ImageButton android:id="@+id/btnFindMe"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:layout_centerInParent="true"
        android:background="@drawable/findme"></ImageButton>
    </RelativeLayout>
    
    Answered on December 17, 2018.
    Add Comment

    Using a LinearLayout, center a button:

    <LinearLayout
      android:id="@+id/LinearLayout1"
      android:layout_width="match_parent"
      android:layout_height="match_parent"
      android:gravity="center"
      android:orientation="vertical" >
     
      <ImageButton
        android:id="@+id/btnFindMe"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:background="@drawable/findme" />
    </LinearLayout>
    
    Answered on December 17, 2018.
    Add Comment

    Try the statement:

         By defining android:gravity=”center_vertical|center_horizontal” inside the layout and setting android:layout_weight=”1″ in the image.

    Answered on December 17, 2018.
    Add Comment


  • Your Answer

    By posting your answer, you agree to the privacy policy and terms of service.