Центрировать две кнопки по горизонтали
Я пытаюсь расположить две кнопки (с изображениями на них, которые работают отлично) рядом друг с другом и центрировать их по горизонтали. Это то, что я до сих пор:
<LinearLayout android:orientation="horizontal" android:layout_below="@id/radioGroup"
android:layout_width="wrap_content" android:layout_height="wrap_content"
android:layout_gravity="center_horizontal|center">
<Button
android:id="@+id/allow"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_below="@id/radioGroup"
android:layout_gravity="center_horizontal"
android:drawableLeft="@drawable/accept_btn"
android:text="Allow"/>
<Button
android:id="@+id/deny"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_toRightOf="@id/allow"
android:layout_below="@id/radioGroup"
android:layout_gravity="center_horizontal"
android:drawableLeft="@drawable/block_btn"
android:text="Deny"/>
</LinearLayout>
К сожалению, они все еще выровнены с левой стороны. Любая помощь приветствуется! Ив
Edit
К сожалению, ни один из комментариев или предложений не работает до сих пор. Вот почему я пытаюсь предоставить упрощенный, полный макет теперь с RelativeLayout:
<?xml version="1.0" encoding="utf-8"?>
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="fill_parent" android:layout_height="wrap_content"
android:layout_centerHorizontal="true">
<TextView android:text="@+id/TextView01" android:id="@+id/TextView01"
android:layout_width="wrap_content" android:layout_height="wrap_content"/>
<Button
android:id="@+id/allow"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_below="@id/TextView01"
android:text="Allow"/>
<Button
android:id="@+id/deny"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_toRightOf="@id/allow"
android:layout_alignTop="@id/allow"
android:text="Deny"/>
</RelativeLayout>
Я пробовал все комбинации атрибутов в LinearLayout и на элементах Button без везения. Любые другие идеи?
Ответы
Ответ 1
Это мое решение:
<?xml version="1.0" encoding="utf-8"?>
<RelativeLayout
xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="fill_parent" android:layout_height="wrap_content"
android:layout_centerHorizontal="true">
<TextView
android:text="@+id/SomeText"
android:id="@+id/TextView01"
android:layout_width="wrap_content" android:layout_height="wrap_content" />
<LinearLayout
android:orientation="horizontal"
android:background="@android:drawable/bottom_bar"
android:paddingLeft="4.0dip"
android:paddingTop="5.0dip"
android:paddingRight="4.0dip"
android:paddingBottom="1.0dip"
android:layout_width="fill_parent" android:layout_height="wrap_content"
android:layout_below="@+id/TextView01">
<Button
android:id="@+id/allow"
android:layout_width="0.0dip" android:layout_height="fill_parent"
android:text="Allow"
android:layout_weight="1.0" />
<Button
android:id="@+id/deny"
android:layout_width="0.0dip" android:layout_height="fill_parent"
android:text="Deny"
android:layout_weight="1.0" />
</LinearLayout>
</RelativeLayout>
Ответ 2
Я знаю, что вы уже нашли решение, но вы также можете найти это полезным. Пустой TextView, используемый в качестве центральной ссылки, может удваиваться как дополнение между кнопками, увеличивая настройку dip. Он также хорошо меняет изменения ориентации экрана.
<RelativeLayout
xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="match_parent"
android:layout_height="match_parent">
<Button
android:id="@+id/button1"
android:text="Left"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_alignParentLeft="true"
android:layout_toLeftOf="@+id/centerPoint" />
<TextView
android:id="@+id/centerPoint"
android:text=""
android:layout_width="0dip"
android:layout_height="wrap_content"
android:layout_centerHorizontal="true" />
<Button
android:id="@+id/button2"
android:text="Right"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_alignParentRight="true"
android:layout_toRightOf="@+id/centerPoint" />
</RelativeLayout>
Снимок экрана результата:
![screen shot of the result]()
Ответ 3
Я не знаю, действительно ли вы нашли хороший ответ на этот вопрос, но я достиг этого, создав TableRow, установив ширину fill_parent и установив гравитацию в центр, а затем разместив две кнопки внутри нее.
<TableRow android:layout_width="fill_parent"
android:layout_height="wrap_content" android:gravity="center">
<Button android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="Test" android:width="100dip"></Button>
<Button android:layout_width="wrap_content"
android:text="Test" android:layout_height="wrap_content"
android:width="100dip"></Button>
</TableRow>
Ответ 4
Если вы ищете быстрое решение RelativeLayout, то работает хорошо.
Элемент Dummy View невидим и центрирован по горизонтали.
Обе кнопки расположены влево или вправо.
<RelativeLayout
xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:app="http://schemas.android.com/apk/res/com.be.android.stopwatch"
android:orientation="vertical"
android:layout_width="fill_parent"
android:layout_height="fill_parent"
android:layout_gravity="center_horizontal">
<View android:id="@+id/dummy" android:visibility="visible" android:layout_height="0dip" android:layout_width="1dip" android:background="#FFFFFF" android:layout_centerHorizontal="true"/>
<ImageButton android:id="@+id/button1" android:layout_height="25dip" android:layout_alignTop="@+id/dummy" android:layout_toLeftOf="@+id/dummy" android:layout_width="50dip"/>
<ImageButton android:id="@+id/button2" android:layout_height="25dip" android:layout_alignTop="@+id/dummy" android:layout_toRightOf="@+id/dummy" android:layout_width="50dip"/>
</RelativeLayout>
Ответ 5
Атрибуты с именем android:layout_foo
представляют собой LayoutParams - аргументы для родителя View. Попробуйте установить android:gravity="center"
на LinearLayout
вместо android:layout_gravity
. Один из них влияет на то, как LinearLayout
выложит своих детей внутри себя, а другой повлияет на то, как родитель LinearLayout
должен его обработать. Вам нужен первый.
Ответ 6
Я центрирую две кнопки таким образом:
<LinearLayout
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:orientation="horizontal" >
<LinearLayout
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_weight="1"
android:orientation="vertical" >
<Button
android:id="@+id/button1"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_gravity="center"
android:text="@string/one" />
</LinearLayout>
<LinearLayout
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_weight="1"
android:orientation="vertical" >
<Button
android:id="@+id/button2"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_gravity="center"
android:text="@string/two" />
</LinearLayout>
</LinearLayout>
Ответ 7
Я обернул два горизонтальных LinearLayout следующим образом:
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:orientation="horizontal"
android:gravity="center"
android:layout_width="fill_parent"
android:layout_height="wrap_content" >
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:orientation="horizontal"
android:layout_width="wrap_content"
android:layout_height="wrap_content" >
виджеты пользовательского интерфейса здесь
</LinearLayout> </LinearLayout>
Ответ 8
Это похоже на очень старый вопрос, но у меня тоже была проблема. Мне пришлось поместить две кнопки рядом друг с другом в середине экрана (по горизонтали). В итоге я разместил две кнопки внутри линейной компоновки и разместил линейную компоновку в относительной компоновке с установленным центром тяжести.
UPDATE: я нашел еще более простое решение:
<LinearLayout android:layout_height="wrap_content" android:layout_width="wrap_content"
android:layout_centerHorizontal="true">
<Button android:text="status" android:layout_height="wrap_content" android:layout_width="wrap_content"/>
<Button android:text="fly" android:layout_height="wrap_content" android:layout_width="wrap_content"/>
</LinearLayout>
Это то, что я имел раньше:
<RelativeLayout android:layout_height="wrap_content" android:layout_width="match_parent"
android:id="@+id/actionButtons" android:layout_below="@id/tripInfo" android:gravity="center">
<LinearLayout android:layout_height="wrap_content" android:layout_width="wrap_content">
<Button android:text="status" android:layout_height="wrap_content" android:layout_width="wrap_content" />
<Button android:text="fly" android:layout_height="wrap_content" android:layout_width="wrap_content" />
</LinearLayout>
</RelativeLayout>
Ответ 9
Используйте Relatie Layout вместо Linear и установите гравитацию как android: gravity = "center" .
Относительные компоновки обеспечивают лучшую производительность и масштабирование лучше, если вы запускаете приложение разных размеров.
Следуя примеру XML и результирующего интерфейса:
<RelativeLayout
android:layout_width="match_parent"
android:layout_height="80dp"
android:background="@Color/custom1"
android:gravity="center" >
<TextView
android:id="@+id/tv1"
android:layout_width="wrap_content"
android:layout_height="50dp"
android:background="@color/Red"
android:gravity="center"
android:layout_marginRight="80dp"
android:text="Text11111" />
<TextView
android:id="@+id/tv2"
android:layout_width="wrap_content"
android:layout_height="50dp"
android:layout_toRightOf="@id/tv1"
android:background="@color/Yellow"
android:gravity="center"
android:text="Text22222" />
</RelativeLayout>
![enter image description here]()
Ответ 10
Это то, что я сделал, я завернул линейный макет с линейным макетом, который имеет гравитацию, установленную в центр_ горизонтальной. Затем я установил ширину линейной компоновки с шириной пикселя в комбинации пикселей. В этом примере кнопки имеют ширину 100 пикселей, поэтому я устанавливаю линейный формат с оболочкой на 200 пикселей.
Пример 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"
android:gravity="center_horizontal">
<TextView android:layout_width="fill_parent"
android:layout_height="200px"
android:text="This is some text!"
android:background="#ff333333" />
<LinearLayout android:layout_height="wrap_content"
android:id="@+id/linearLayout1"
android:layout_width="200px">
<Button android:id="@+id/button1"
android:layout_height="wrap_content"
android:text="Button 1"
android:layout_width="100px">
</Button>
<Button android:id="@+id/button2"
android:layout_height="wrap_content"
android:text="Button 2"
android:layout_width="100px">
</Button>
</LinearLayout>
</LinearLayout>
Ответ 11
Это мое решение, используя relativeLayout:
<RelativeLayout
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:gravity="center">
<Button
android:id="@+id/reject_btn"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="@string/reject"/>
<Button
android:id="@+id/accept_btn"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="@string/accept"
android:layout_toRightOf="@id/reject_btn"/>
</RelativeLayout>
Ответ 12
Используйте RelativeLayout
вместо LinearLayout
и установите его android_layout:gravity="center_horizontal"
или очень не оптимальный способ - установить android_padding
из LinearLayout
с значениями пикселей, выравнивая их по центру.
Ответ 13
Я чувствую вашу боль, мне пришлось немного подкорректировать ситуацию и заставить ее работать.
<?xml version="1.0" encoding="utf-8"?>
<RelativeLayout
xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="wrap_content"
android:layout_height="wrap_content">
<Button
android:id="@+id/Button01"
android:layout_alignParentLeft="true"
android:layout_width="75dp"
android:layout_height="40dp"
android:layout_marginTop="15dp"
android:layout_marginLeft="60dp"
android:text="No" />
<Button
android:id="@+id/Button02"
android:layout_alignParentRight="true"
android:layout_width="75dp"
android:layout_height="40dp"
android:layout_marginTop="15dp"
android:layout_marginRight="60dp"
android:text="Yes" />
<TextView
android:id="@+id/centerPoint"
android:layout_toRightOf="@id/Button01"
android:layout_toLeftOf="@id/Button02"
android:text=""
android:layout_width="0dip"
android:layout_height="wrap_content"
android:layout_centerHorizontal="true"
/>
</RelativeLayout>
Ответ 14
Это сработало очень хорошо для меня:
<RadioGroup
android:id="@+id/ratingRadioGroup"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:orientation="horizontal"
android:layout_gravity="center_horizontal">
<RadioButton
android:id="@+id/likeButton"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:checked="true"
android:text="@string/like"
android:paddingRight="20pt"/>
<RadioButton
android:id="@+id/dislikeButton"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="@string/dislike" />
</RadioGroup>
Ответ 15
Самый элегантный способ сделать это без введения избыточных компонентов или групп просмотра - использовать интервал. Вы можете использовать элементы пространства с layout_weight в линейном макете, чтобы получить необходимый эффект:
<LinearLayout android:orientation="horizontal" android:layout_below="@id/radioGroup"
android:layout_width="wrap_content" android:layout_height="wrap_content"
android:layout_gravity="center_horizontal|center">
<Space
android:layout_width="wrap_content"
android:layout_height="match_parent"
android:layout_weight="1" />
<Button
android:id="@+id/allow"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_below="@id/radioGroup"
android:drawableLeft="@drawable/accept_btn"
android:text="Allow"/>
<Button
android:id="@+id/deny"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_toRightOf="@id/allow"
android:layout_below="@id/radioGroup"
android:drawableLeft="@drawable/block_btn"
android:text="Deny"/>
<Space
android:layout_width="wrap_content"
android:layout_height="match_parent"
android:layout_weight="1" />
</LinearLayout>
Предоставляя обе элементам пространства равный layout_weight (не имеет значения, какие веса, он просто принимает их как отношение из итогов всех весов) заставляет элементы пространства занимать дополнительное пространство, доступное. Поэтому он заставляет кнопки посередине, которые не имеют назначенного им макета, поэтому они не занимают лишнее пространство, просто то, что они явно указаны (размер изображений).
Ответ 16
Ниже код выравнивает две кнопки в центре по горизонтали, не указывается dp. Таким образом, это будет работать во всех ориентациях и на всех экранах.
<LinearLayout
android:orientation="horizontal"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_gravity="center_horizontal"
>
<Button
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="Change password"
android:id="@+id/change_pwd_button"
android:layout_gravity="center_horizontal"
android:background="@android:color/holo_blue_dark"
android:textColor="@android:color/white"
android:padding="25px"/>
<Button
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="Close"
android:id="@+id/change_pwd_close_btn"
android:layout_gravity="center_horizontal"
android:background="@android:color/holo_blue_dark"
android:textColor="@android:color/white"
android:layout_marginLeft="20dp"
/>
</LinearLayout>
Ответ 17
эта работа для меня. просто и легко.
<RelativeLayout
android:layout_width="match_parent"
android:layout_height="match_parent">
<LinearLayout
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_centerInParent="true"
>
<RelativeLayout
android:layout_width="wrap_content"
android:layout_height="wrap_content">
<Button
android:id="@+id/btn_one"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="Button One"
/>
<Button
android:id="@+id/btn_two"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="Button Two"
android:layout_toRightOf="@id/btn_one"
/>
</RelativeLayout>
</LinearLayout>
</RelativeLayout>