Center a button in a Linear layout

后端 未结 19 1276
遇见更好的自我
遇见更好的自我 2020-12-04 04:55

I am using a linear layout to display a pretty light initial screen. It has 1 button that is supposed to centre in the screen both horizontally and vertically. However no

相关标签:
19条回答
  • 2020-12-04 05:25

    If you use LinearLayout you can add gravity center:

    <LinearLayout
            android:layout_width="match_parent"
            android:layout_height="wrap_content"
            android:orientation="vertical"
            android:gravity="center">
                <Button
                android:layout_width="200dp"
                android:layout_height="wrap_content"
                />
    </LinearLayout>`
    
    0 讨论(0)
  • 2020-12-04 05:26
    <?xml version="1.0" encoding="utf-8"?>
    <LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
        android:orientation="vertical"
        android:layout_width="fill_parent"
        android:layout_height="fill_parent">
    
        <ImageButton android:id="@+id/btnFindMe" 
            android:layout_width="match_parent" 
            android:layout_height="wrap_content"
            android:layout_gravity = "center"
            android:background="@drawable/findme">
        </ImageButton>
    
    </LinearLayout>
    

    The above code will work.

    0 讨论(0)
  • 2020-12-04 05:27

    As per the Android documentation for XML Attributes of android:layout_gravity, we can do it easily :)

    <?xml version="1.0" encoding="utf-8"?>
    <LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
        android:orientation="vertical"
        android:layout_width="match_parent"
        android:layout_height="match_parent">
    
        <ImageButton android:id="@+id/btnFindMe" 
            android:layout_width="wrap_content" 
            android:layout_height="wrap_content"
    
            android:layout_gravity="center"
    
            android:background="@drawable/findme"></ImageButton>
    
    </LinearLayout>
    
    0 讨论(0)
  • 2020-12-04 05:28

    It would be easier to use relative layouts, but for linear layouts I usually center by making sure the width matches parent :

        android:layout_width="match_parent"
    

    and then just give margins to right and left accordingly.

        android:layout_marginLeft="20dp"
        android:layout_marginRight="20dp"
    
    0 讨论(0)
  • 2020-12-04 05:29

    use

    android:layout_centerHorizontal="true"

    0 讨论(0)
  • 2020-12-04 05:31

    This is working for me.

    android:layout_alignParentEnd="true"
    
    0 讨论(0)
提交回复
热议问题