Центрировать кнопку в линейном макете

291

Я использую линейную компоновку для отображения довольно легкого начального экрана. Он имеет 1 кнопку, которая должна располагаться на экране как по горизонтали, так и по вертикали. Однако независимо от того, что я пытаюсь сделать, кнопка будет располагаться по центру. Я включил XML ниже, может ли кто-нибудь указать мне в правильном направлении?

Спасибо

<?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="wrap_content" 
        android:layout_height="wrap_content"
        android:layout_gravity="center_vertical|center_horizontal"
        android:background="@drawable/findme"></ImageButton>

</LinearLayout>
  • 6
    Что исправило это для меня в LinearLayout с горизонтальным выравниванием, так это установило layout_width в "wrap_content". Впоследствии layout_gravity сделал то, что должен был сделать!
  • 0
    Если вам строго необходимо использовать LinearLayout, я думаю, что это должно работать: stackoverflow.com/questions/18051472/…
Теги:
layout

16 ответов

340
Лучший ответ

Если вы хотите центрировать элемент в середине экрана, не используйте LinearLayout, поскольку они предназначены для отображения нескольких элементов в строке.

Используйте RelativeLayout.

Итак, замените:

android:layout_gravity="center_vertical|center_horizontal"

для соответствующей опции RelativeLayout:

android:layout_centerInParent="true"

Итак, ваш файл макета будет выглядеть так:

<?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>
  • 0
    Отлично, я должен был попробовать RelativeLayout раньше!
  • 33
    Есть случаи, когда вам нужно использовать LinearLayout и центрировать контент. Это не должно быть принятым ответом. Было бы лучше предложить использовать RelativeLayout, если это возможно, а если нет, то как центрировать его в LinearLayout.
Показать ещё 1 комментарий
376

Центр с использованием LinearLayout:

<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>
  • 10
    LinearLayout проще и легче по сравнению с RelativeLayout, должен быть немного быстрее.
  • 3
    Я использовал layout_gravity вместо гравитации. переход на андроид: gravity = "center" исправил это для меня. ошибка новичка.
Показать ещё 1 комментарий
39

Вы пытались определить android:gravity="center_vertical|center_horizontal" внутри макета и установить android:layout_weight="1" на изображении?

  • 2
    Мне нравится эта опция, которая позволяет мне сохранить мой LinearLayout! (Мне не нужно было устанавливать android:weight="1" в кнопке, чтобы отцентрировать его.)
  • 4
    Android: гравитация не работает для меня в горизонтальном LinearLayout, но Android: layout_gravity работает.
30

Обычно используемый метод, который работает с линейной компоновкой, заключается в установке свойства на кнопку изображения

android:layout_gravity="center"

Вы можете выбрать выравнивание по левому краю, выравнивание по центру или выравнивание по правому краю каждого объекта в линейном макете. Обратите внимание, что указанная выше строка точно такая же, как

android:layout_gravity="center_vertical|center_horizontal"
  • 4
    .... Я пытался сделать это, черт возьми ... никогда не работает .....
  • 4
    Добавьте свойство android: gravity = "center" в родительский макет, который содержит вашу кнопку (дочерние компоненты).
Показать ещё 1 комментарий
7

легко с этим

    <LinearLayout
        android:layout_width="match_parent"
        android:layout_height="match_parent"
        android:layout_weight="1"
        android:visibility="visible" 
        android:gravity="center"
        android:orientation="vertical" >

        <ProgressBar
            android:id="@+id/pbEndTrip"
            android:layout_width="wrap_content"
            android:layout_height="wrap_content"
            android:layout_gravity="center"
            />

        <TextView
            android:layout_width="match_parent"
            android:layout_height="wrap_content"
            android:layout_marginTop="10dp"
            android:gravity="center"
            android:text="Gettings" />
    </LinearLayout>
5

Добавьте это

android:gravity="center"

В LinearLayout.

  • 1
    должен быть android:gravity="center"
5

Вы можете использовать RelativeLayout.

4
<?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>

Вышеприведенный код будет работать.

2

полный и рабочий образец с моей машины...

<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:tools="http://schemas.android.com/tools"
    android:layout_width="fill_parent"
    android:layout_height="fill_parent"
    android:paddingLeft="@dimen/activity_horizontal_margin"
    android:paddingRight="@dimen/activity_horizontal_margin"
    android:paddingTop="@dimen/activity_vertical_margin"
    android:paddingBottom="@dimen/activity_vertical_margin"
    android:orientation="vertical"
    tools:context=".MainActivity"
    android:gravity="center"
    android:textAlignment="center">


    <TextView
        android:layout_width="fill_parent"
        android:layout_height="wrap_content"
        android:textAppearance="?android:attr/textAppearanceLarge"
        android:text="My Apps!"
        android:id="@+id/textView"
        android:gravity="center"
        android:layout_marginBottom="20dp"
     />

    <Button
        android:layout_width="220dp"
        android:layout_height="wrap_content"
        android:text="SPOTIFY STREAMER"
        android:id="@+id/button_spotify"
        android:gravity="center"
        android:layout_below="@+id/textView"
        android:padding="20dp"
        />

    <Button
        android:layout_width="220dp"
        android:layout_height="wrap_content"
        android:text="SCORES"
        android:id="@+id/button_scores"
        android:gravity="center"
        android:layout_below="@+id/textView"
        android:padding="20dp"
        />


    <Button
        android:layout_width="220dp"
        android:layout_height="wrap_content"
        android:layout_centerInParent="true"
        android:text="LIBRARY APP"
        android:id="@+id/button_library"
        android:gravity="center"
        android:layout_below="@+id/textView"
        android:padding="20dp"
        />

    <Button
        android:layout_width="220dp"
        android:layout_height="wrap_content"
        android:layout_centerInParent="true"
        android:text="BUILD IT BIGGER"
        android:id="@+id/button_buildit"
        android:gravity="center"
        android:layout_below="@+id/textView"
        android:padding="20dp"
        />

    <Button
        android:layout_width="220dp"
        android:layout_height="wrap_content"
        android:layout_centerInParent="true"
        android:text="BACON READER"
        android:id="@+id/button_bacon"
        android:gravity="center"
        android:layout_below="@+id/textView"
        android:padding="20dp"
        />

    <Button
        android:layout_width="220dp"
        android:layout_height="wrap_content"
        android:layout_centerInParent="true"
        android:text="CAPSTONE: MY OWN APP"
        android:id="@+id/button_capstone"
        android:gravity="center"
        android:layout_below="@+id/textView"
        android:padding="20dp"
        />

</LinearLayout>
  • 0
    вы можете использовать «android: layout_below» только для братьев и сестер «RelativeLayout»
1

Согласно документации Android для атрибутов XML android:layout_gravity, мы можем сделать это легко:)

<?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>
  • 1
    android: layout_gravity = "center" работает отлично :) спасибо!
0

Установите значение true android:layout_alignParentTop="true" и android:layout_centerHorizontal="true" в кнопке, например:

<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:tools="http://schemas.android.com/tools"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    >
     <Button
        android:id="@+id/switch_flashlight"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:text="@string/turn_on_flashlight"
        android:textColor="@android:color/black"
        android:onClick="action_trn"
        android:background="@android:color/holo_green_light"
        android:layout_alignParentTop="true"
        android:layout_centerHorizontal="true"
        android:padding="5dp" />
</RelativeLayout>

Изображение 4507

0

просто используйте (чтобы сделать его в центре вашего макета)

        android:layout_gravity="center" 

и используйте

         android:layout_marginBottom="80dp"

         android:layout_marginTop="80dp"

изменить положение

0

Вы также можете попробовать этот код:

<LinearLayout
            android:id="@+id/linear_layout"
            android:layout_width="fill_parent"
            android:layout_height="0dp"
            android:layout_gravity="center"
            android:orientation="horizontal"
            android:weightSum="2.0"
            android:background="@drawable/anyBackground" >

        <LinearLayout
            android:layout_width="match_parent"
            android:layout_height="wrap_content"
            android:layout_gravity="center"
            android:orientation="vertical"
            android:layout_weight="1" >

            <ImageView
                android:id="@+id/img_mail"
                android:layout_width="wrap_content"
                android:layout_height="wrap_content"
                android:layout_gravity="center"
                android:background="@drawable/yourImage" />
        </LinearLayout>

        <LinearLayout
            android:layout_width="match_parent"
            android:layout_height="wrap_content"
            android:layout_gravity="center"
            android:orientation="vertical"
            android:layout_weight="1" >



<ImageView
            android:id="@+id/img_save"
            android:layout_width="wrap_content"
            android:layout_height="match_parent"
            android:layout_gravity="center"
            android:background="@drawable/yourImage" />
        </LinearLayout>
        </LinearLayout>
  • 0
    Можете ли вы объяснить, чем это отличается от уже предоставленных ответов?
-1

Вы пробовали это?

  <TableLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:id="@+id/mainlayout" android:orientation="vertical"
android:layout_width="fill_parent" android:layout_height="fill_parent">
<RelativeLayout
android:layout_width="fill_parent"
android:layout_height="wrap_content"
android:padding="5px"
android:background="#303030"
>
    <RelativeLayout
    android:id="@+id/widget42"
    android:layout_width="wrap_content"
    android:layout_height="wrap_content"
    android:layout_centerHorizontal="true"
    >
    <ImageButton
    android:id="@+id/map"
    android:layout_width="wrap_content"
    android:layout_height="wrap_content"
    android:text="map"
    android:src="@drawable/outbox_pressed"
    android:background="@null"
    android:layout_toRightOf="@+id/location"
    />
    <ImageButton
    android:id="@+id/location"
    android:layout_width="wrap_content"
    android:layout_height="wrap_content"
    android:text="location"
    android:src="@drawable/inbox_pressed"
    android:background="@null"
    />
    </RelativeLayout>
    <ImageButton
    android:id="@+id/home"
    android:src="@drawable/button_back"
    android:background="@null"
    android:layout_width="wrap_content"
    android:layout_height="wrap_content"
    android:layout_centerVertical="true"
    />
</RelativeLayout>
<LinearLayout
android:layout_width="fill_parent"
android:layout_height="wrap_content"
android:padding="5px"
android:orientation="horizontal"
android:background="#252525"
>
    <EditText
    android:id="@+id/searchfield"
    android:layout_width="fill_parent"
    android:layout_weight="1"
    android:layout_height="wrap_content"
    android:layout_centerHorizontal="true"
    android:background="@drawable/customshape"
    />
    <ImageButton
    android:id="@+id/search_button"
    android:src="@drawable/search_press"
    android:background="@null"
    android:layout_width="wrap_content"
    android:layout_height="wrap_content"
    android:layout_centerVertical="true"
    />
</LinearLayout>
<com.google.android.maps.MapView
    android:id="@+id/mapview" 
    android:layout_weight="1"
    android:layout_width="fill_parent"
    android:layout_height="wrap_content" 
    android:clickable="true"
    android:apiKey="apikey" />

</TableLayout>
-2

использовать

Android: layout_centerHorizontal = "истина"

  • 0
    Какие??? Это мусор, это даже не действительная собственность!
  • 1
    На самом деле vogon101, это допустимое свойство в RelativeLayout. :) Это не отвечает на вопрос, потому что пользователь использовал LinearLayout и хотел центрировать как вертикально, так и горизонтально.
-7

Было бы проще использовать относительные макеты, но для линейных макетов я обычно центрируюсь, убедившись, что ширина соответствует родительскому:

    android:layout_width="match_parent"

а затем просто дайте поля соответственно справа и слева.

    android:layout_marginLeft="20dp"
    android:layout_marginRight="20dp"

Ещё вопросы

Сообщество Overcoder
Наверх
Меню