Кнопка Right Align в горизонтальном LinearLayout
Просто быстрый глупый вопрос. Если вы посмотрите на прикрепленное изображение. Мне нужно, чтобы моя кнопка была выровнена по правому краю, но по какой-то причине она не работает с "гравитацией: правильно"...
![enter image description here]()
Здесь мой код для этого макета:
<LinearLayout
xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="fill_parent"
android:layout_height="wrap_content"
android:orientation="horizontal"
android:layout_marginTop="35dp">
<TextView
android:id="@+id/lblExpenseCancel"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="@string/cancel"
android:textColor="#404040"
android:layout_marginLeft="10dp"
android:textSize="20sp"
android:layout_marginTop="9dp" />
<Button
android:id="@+id/btnAddExpense"
android:layout_width="wrap_content"
android:layout_height="45dp"
android:background="@drawable/stitch_button"
android:layout_marginLeft="10dp"
android:text="@string/add"
android:layout_gravity="right"
android:layout_marginRight="15dp" />
</LinearLayout>
Почему нет работы?! Спасибо, ребята...
Ответы
Ответ 1
Используйте следующий код для этого
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="fill_parent"
android:layout_height="wrap_content"
android:layout_marginTop="35dp"
android:orientation="horizontal" >
<TextView
android:id="@+id/lblExpenseCancel"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_marginLeft="10dp"
android:layout_marginTop="9dp"
android:text="@string/cancel"
android:textColor="#404040"
android:textSize="20sp" />
<Button
android:id="@+id/btnAddExpense"
android:layout_width="wrap_content"
android:layout_height="45dp"
android:layout_alignParentRight="true"
android:layout_marginLeft="10dp"
android:layout_marginRight="15dp"
android:background="@drawable/stitch_button"
android:text="@string/add" />
</RelativeLayout>
Ответ 2
Единое решение LinearLayout
. Только добавление простого интервала:
(Никто, похоже, не упомянул об этом, только более сложные решения с несколькими макетами.)
<LinearLayout
xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="fill_parent"
android:layout_height="wrap_content"
android:orientation="horizontal"
android:layout_marginTop="35dp">
<TextView
android:id="@+id/lblExpenseCancel"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="@string/cancel"
android:textColor="#404040"
android:layout_marginLeft="10dp"
android:textSize="20sp"
android:layout_marginTop="9dp" />
<!------------------------- ADDED SPACER VIEW -------------------->
<View
android:layout_width="0dp"
android:layout_height="0dp"
android:layout_weight="1"
/>
<!------------------------- /ADDED SPACER VIEW -------------------->
<Button
android:id="@+id/btnAddExpense"
android:layout_width="wrap_content"
android:layout_height="45dp"
android:background="@drawable/stitch_button"
android:layout_marginLeft="10dp"
android:text="@string/add"
android:layout_gravity="right"
android:layout_marginRight="15dp" />
</LinearLayout>
Обратите внимание на "выделенный" вид, я ничего не изменил. Высота = 0 гарантирует, что она не видна. Ширина = 0, потому что ширина определяется LinearLayout
на основе веса = 1. Это означает, что спейсерный вид будет как можно больше растягиваться в направлении (ориентации) LinearLayout
.
Обратите внимание, что вы должны использовать android.widget.Space
или android.support.v4.widget.Space
вместо View
, если ваш уровень API и/или зависимости разрешают его. Space
выполняет работу более дешевым способом, поскольку она только измеряет и не пытается нарисовать что-либо вроде View
; это также более выразительно передает намерение.
Ответ 3
Я знаю, что этот вопрос был задан некоторое время назад, но я сделал это раньше, и это позволяет контролировать больше при выравнивании элементов. Если вы посмотрите на него, как на веб-программирование, это помогает. Вы просто вложите еще один LinearLayout
, который будет содержать вашу кнопку внутри него. Затем вы можете изменить масштаб макета кнопки и повернуть его вправо, пока TextView
все еще находится слева.
Попробуйте этот код:
<LinearLayout
xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="fill_parent"
android:layout_height="wrap_content"
android:orientation="horizontal"
android:layout_marginTop="35dp">
<TextView
android:id="@+id/lblExpenseCancel"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="@string/cancel"
android:textColor="#404040"
android:layout_marginLeft="10dp"
android:textSize="20sp"
android:layout_marginTop="9dp"/>
<LinearLayout
android:layout_width="fill_parent"
android:layout_height="wrap_content"
android:gravity="right"
android:orientation="horizontal" >
<Button
android:id="@+id/btnAddExpense"
android:layout_width="wrap_content"
android:layout_height="45dp"
android:background="@drawable/stitch_button"
android:layout_marginLeft="10dp"
android:text="@string/add"
android:layout_gravity="right"
android:layout_marginRight="15dp"/>
</LinearLayout>
Возможно, вам придется играть с заполнением на вложенном макете, чтобы он действовал так, как вы хотите.
Ответ 4
попробуйте этот
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout
xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="fill_parent"
android:layout_gravity="right"
android:layout_height="wrap_content"
android:orientation="horizontal" >
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="fill_parent"
android:layout_height="wrap_content"
android:orientation="horizontal" >
<TextView
android:id="@+id/lblExpenseCancel"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_marginLeft="10dp"
android:layout_marginTop="9dp"
android:text="cancel"
android:textColor="#ffff0000"
android:textSize="20sp" />
<Button
android:id="@+id/btnAddExpense"
android:layout_width="wrap_content"
android:layout_height="45dp"
android:layout_alignParentRight="true"
android:layout_marginLeft="10dp"
android:layout_marginRight="15dp"
android:textColor="#ff0000ff"
android:text="add" />
</RelativeLayout>
</LinearLayout>
Ответ 5
Как уже упоминалось несколько раз раньше: Для переключения с LinearLayout на RelativeLayout работает, но вы также можете решить проблему, а не избегать ее. Используйте инструменты, которые предоставляет LinearLayout: Дайте TextView весу = 1 (см. Код ниже), вес вашей кнопки должен оставаться 0 или никем. В этом случае TextView займет все оставшееся пространство, которое не используется для отображения содержимого вашего TextView или ButtonView и нажимает кнопку вправо.
<LinearLayout
xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="fill_parent"
android:layout_height="wrap_content"
android:orientation="horizontal"
android:layout_marginTop="35dp">
<TextView
android:id="@+id/lblExpenseCancel"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="@string/cancel"
android:textColor="#404040"
android:layout_marginLeft="10dp"
android:textSize="20sp"
android:layout_marginTop="9dp"
**android:layout_weight="1"**
/>
<Button
android:id="@+id/btnAddExpense"
android:layout_width="wrap_content"
android:layout_height="45dp"
android:background="@drawable/stitch_button"
android:layout_marginLeft="10dp"
android:text="@string/add"
android:layout_gravity="right"
android:layout_marginRight="15dp" />
</LinearLayout>
Ответ 6
Реальное решение для этого случая:
android:layout_weight="1"
для TextView, и ваша кнопка перемещается вправо!
Ответ 7
Вам нужно добавить гравитацию к макету, а не кнопке, настройка силы тяжести в кнопке - для текста внутри кнопки
<LinearLayout
xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="fill_parent"
android:layout_gravity="right"
android:layout_height="wrap_content"
android:orientation="horizontal"
android:layout_marginTop="35dp">
Ответ 8
<LinearLayout
xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="fill_parent"
android:layout_height="wrap_content"
android:orientation="horizontal"
android:layout_marginTop="35dp">
<TextView
android:id="@+id/lblExpenseCancel"
android:layout_width="0dp"
android:layout_weight="0.5"
android:layout_height="wrap_content"
android:text="@string/cancel"
android:textColor="#404040"
android:layout_marginLeft="10dp"
android:textSize="20sp"
android:layout_marginTop="9dp"/>
<Button
android:id="@+id/btnAddExpense"
android:layout_width="0dp"
android:layout_weight="0.5"
android:layout_height="wrap_content"
android:background="@drawable/stitch_button"
android:layout_marginLeft="10dp"
android:text="@string/add"
android:layout_gravity="right"
android:layout_marginRight="15dp"/>
</LinearLayout>
Это решит вашу проблему.
Ответ 9
Я использовал аналогичную компоновку с 4 TextView
s. Два TextView
должны быть выровнены влево, а два TextView
должны быть выровнены вправо. Итак, вот мое решение, если вы хотите использовать только LinearLayouts
.
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:orientation="horizontal"
android:baselineAligned="false"
android:padding="10dp" >
<LinearLayout
android:layout_width="0dip"
android:layout_weight="0.50"
android:layout_height="match_parent"
android:gravity="left"
android:orientation="horizontal" >
<TextView
android:id="@+id/textview_fragment_mtfstatus_level"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="@string/level"
android:textAppearance="?android:attr/textAppearanceMedium" />
<TextView
android:id="@+id/textview_fragment_mtfstatus_level_count"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text=""
android:textAppearance="?android:attr/textAppearanceMedium" />
</LinearLayout>
<LinearLayout
android:layout_width="0dip"
android:layout_weight="0.50"
android:layout_height="match_parent"
android:gravity="right"
android:orientation="horizontal" >
<TextView
android:id="@+id/textview_fragment_mtfstatus_time"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="@string/time"
android:textAppearance="?android:attr/textAppearanceMedium"
/>
<TextView
android:id="@+id/textview_fragment_mtfstatus_time_count"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text=""
android:textAppearance="?android:attr/textAppearanceMedium"
/>
</LinearLayout>
</LinearLayout>
Ответ 10
Вы можете использовать RelativeLayout или установить гравитацию = "право" на родительский макет вашей кнопки.
Ответ 11
Я знаю, что это старый, но вот еще один в линейной компоновке:
<LinearLayout
xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="fill_parent"
android:layout_height="wrap_content"
android:orientation="horizontal"
android:layout_marginTop="35dp">
<TextView
android:id="@+id/lblExpenseCancel"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="@string/cancel"
android:textColor="#404040"
android:layout_marginLeft="10dp"
android:textSize="20sp"
android:layout_marginTop="9dp" />
<Button
android:id="@+id/btnAddExpense"
android:layout_width="wrap_content"
android:layout_height="45dp"
android:background="@drawable/stitch_button"
android:layout_marginLeft="10dp"
android:text="@string/add"
android:layout_gravity="center_vertical|bottom|right|top"
android:layout_marginRight="15dp" />
Обратите внимание на layout_gravity, а не на гравитацию.
Ответ 12
Вы должны использовать Relativelayout вместо Linringayout в качестве основного макета. Если вы используете Relativelayout в качестве основного, тогда легко обращайтесь с кнопкой на правой стороне, потому что относительная компоновка обеспечивает выравнивание поровну справа, слева, сверху и снизу.
Ответ 13
Просто добавьте android: gravity = "right" этот макет родительского макета этой строки.
<LinearLayout
android:id="@+id/withdrawbuttonContainer"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:layout_alignParentBottom="true"
android:background="@color/colorPrimary"
android:orientation="horizontal"
**android:gravity="right"**
android:weightSum="5"
android:visibility="visible">
<Button
android:id="@+id/bt_withDraw"
android:layout_width="0dp"
android:layout_height="wrap_content"
android:layout_weight="1"
android:text="@string/BTN_ADD"
app:delay="1500" />
<Button
android:id="@+id/btn_orderdetail_amend"
android:layout_width="0dp"
android:layout_height="wrap_content"
android:layout_weight="1"
android:text="@string/BTN_CANCEL"
app:delay="1500" />
</LinearLayout>
Ответ 14
Если вы не хотите или не можете использовать RelativeLayout, вы можете обернуть кнопку в LinearLayout с ориентацией "по вертикали" и шириной "fill_parent".
<LinearLayout
xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="fill_parent"
android:layout_height="wrap_content"
android:orientation="horizontal"
android:layout_marginTop="35dp">
<TextView
android:id="@+id/lblExpenseCancel"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="@string/cancel"
android:textColor="#404040"
android:layout_marginLeft="10dp"
android:textSize="20sp"
android:layout_marginTop="9dp" />
<LinearLayout
android:layout_width="fill_parent"
android:layout_height="wrap_content"
android:orientation="vertical">
<Button
android:id="@+id/btnAddExpense"
android:layout_width="wrap_content"
android:layout_height="45dp"
android:background="@drawable/stitch_button"
android:layout_marginLeft="10dp"
android:text="@string/add"
android:layout_gravity="right"
android:layout_marginRight="15dp" />
</LinearLayout>
</LinearLayout>
Это связано с тем, что если ориентация LinearLayout горизонтальна, гравитация влияет только на представления по вертикали. И если ориентация "вертикальная", гравитация влияет только на точки зрения по горизонтали. См. здесь для получения более подробной информации о пояснении LinearLayout/гравитации.
Ответ 15
Используйте ширину макета в кнопке, например, android: layout_width = "75dp"