LinearLayout: layout_gravity = "bottom" не работает в горизонтальном LinearLayout
Хорошо. Прежде всего, я искал весь интернет, но никто не имеет подобной проблемы. Итак, все, что я хочу, это иметь 3 textViews, нижний выровненный с экраном и с одинаковой шириной. Вот изображение, представляющее то, что я хочу:
![enter image description here]()
И вот мой код:
<RelativeLayout android:layout_width="match_parent" android:layout_height="match_parent">
<LinearLayout
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:layout_alignParentBottom="true">
<TextView
android:text="@string/help_1"
android:layout_weight="0.33"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:background="@drawable/mynicebg1"
android:layout_gravity="bottom"/>
<TextView
android:text="@string/help_2"
android:layout_weight="0.33"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:background="@drawable/mynicebg2"
android:layout_gravity="bottom"/>
<TextView
android:text="@string/help_3"
android:layout_weight="0.33"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:background="@drawable/mynicebg3"
android:layout_gravity="bottom"/>
</LinearLayout>
</RelativeLayout>
Ну, это работает, когда 3 textViews имеют одинаковую высоту, но когда их размер отличается, я получаю следующий результат:
![problem]()
Другим странным поведением является то, что когда я устанавливаю layout_gravity самого большого текста в "center-vertical", я получаю следующий результат:
![first workaround]()
Итак, я сошел с ума и попробовал другие комбинации с вертикальной вертикалью, но ничего не сработало, как я хотел изначально:
![desperation workaround]()
Итак, какие-нибудь советы о том, как это решить?
Ответы
Ответ 1
Правильный ответ
Все остальные ответы неверны. Важные моменты:
- Вам не нужно
RelativeLayout
. Вы можете сделать это только с помощью LinearLayout
.
- (Не критично, но, я думаю, вы не знали). Ваши веса не должны суммироваться до 1, вы можете просто установить их все на любое равное значение (например, 1).
- Критическая вещь: вам нужно
android:baselineAligned="false"
. Я действительно нашел это, просмотрев источник LinearLayout
. Это в документах, но они не упоминают, что он включен по умолчанию!
В любом случае, вот код:
<?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:baselineAligned="false">
<TextView
android:text="dfg dfg dfg dfg dfg dfg dfg dfg dfg dfg dfg dfg dfg dfg dfg dfg dfg dfg dfg dfg"
android:layout_weight="1"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:background="#eeffee"
android:layout_gravity="bottom"/>
<TextView
android:text="asd asd asd asd asd asd asd asd asd asd"
android:layout_weight="1"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:background="#eeeeff"
android:layout_gravity="bottom"/>
<TextView
android:text="qweoiu qweoiuqwe oiqwe qwoeiu qweoiu qweoiuq weoiuqw eoiquw eoiqwue oqiweu qowieu qowieu qoiweu qowieu qowieu qowieu qowieu qoiweu qowieu qoiwue "
android:layout_weight="1"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:background="#ffeeee"
android:layout_gravity="bottom"/>
</LinearLayout>
И как это выглядит:
![Good linear layout]()
Ответ 2
Ok. Таким образом, у меня была такая же проблема, но с кнопками переключения вместо текстовых просмотров. По какой-то причине, если один из элементов LinearLayout (Горизонтальный) имеет разную высоту, чем остальные виды в макете, и имеет тот же вес, что и другие, гравитация эффективно "игнорируется".
Мне удалось добиться желаемого поведения, обернув каждое представление внутри RelativeLayout и установив android: gravity на относительный макет вместо android: layout_gravity на каждой кнопке. Я также переместил android: layout_weight от кнопки к относительной компоновке.
Итак, вместо того, чтобы:
<LinearLayout
... >
<ToggleButton
...
android:layout_height="wrap_content"
android:layout_width="fill_parent"
android:layout_weight="1"
android:layout_gravity="bottom"/>
<ToggleButton
...
android:layout_height="wrap_content"
android:layout_width="fill_parent"
android:layout_weight="1"
android:layout_gravity="bottom"/>
<ToggleButton
...
android:layout_height="wrap_content"
android:layout_width="fill_parent"
android:layout_weight="1"
android:layout_gravity="bottom"/>
</LinearLayout>
Что дает ту же проблему, что и сообщалось, я вместо этого сделал:
<LinearLayout
... >
<RelativeLayout
...
android:layout_width="fill_parent"
android:layout_height="fill_parent"
android:layout_weight="1"
android:gravity="bottom" >
<ToggleButton
...
android:layout_height="wrap_content"
android:layout_width="fill_parent"
/>
<RelativeLayout
...
android:layout_width="fill_parent"
android:layout_height="fill_parent"
android:layout_weight="1"
android:gravity="bottom" >
<ToggleButton
...
android:layout_height="wrap_content"
android:layout_width="fill_parent"
/>
<RelativeLayout
...
android:layout_width="fill_parent"
android:layout_height="fill_parent"
android:layout_weight="1"
android:gravity="bottom" >
<ToggleButton
...
android:layout_height="wrap_content"
android:layout_width="fill_parent"
/>
</LinearLayout>
Ответ 3
** EDIT:
Если это не все, добавьте флаг baselinealigned, как указано в одном из ответов ниже Тимммм. Это лучший способ.
Используйте это
EDITED LAYOUT:
Хорошо, я отредактировал его, а также добавил цвета и гравитацию, чтобы текстуры внизу имели равную высоту и ширину, а также выравнивали текст внизу и в центре каждого вида.
<LinearLayout
android:orientation="horizontal"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:layout_alignParentBottom="true"
android:gravity="fill_vertical" >
<TextView
android:layout_width="match_parent"
android:layout_height="match_parent"
android:layout_weight="1.0"
android:layout_gravity="fill_vertical"
android:gravity="bottom|center"
android:text="text1 jkjhh jhguk jvugy v ghjv kjhvygvusdioc jgytuayhashg hgyff"
android:textColor="#000000"
android:background="#FFFF00"
/>
<TextView
android:layout_width="match_parent"
android:layout_height="match_parent"
android:layout_weight="1.0"
android:layout_gravity="fill_vertical"
android:gravity="bottom|center"
android:text="t2"
android:textColor="#000000"
android:background="#FF0000"
/>
<TextView
android:layout_width="match_parent"
android:layout_height="match_parent"
android:layout_weight="1.0"
android:layout_gravity="fill_vertical"
android:gravity="bottom|center"
android:text="This is a long text. This is a long text. This is a long text. This is a long text.This is a long text. This is a long text. This is a long text."
android:textColor="#000000"
android:background="#00FF00"
/>
</LinearLayout>
Он должен делать именно то, что вы просили.
Он использует LinearLayout внутри RelativeLayout, но иногда требуется, чтобы они вставляли их, чтобы получить то, что мы хотим. Добавьте любые другие виды, которые могут потребоваться в относительном макете, и вы всегда будете иметь свои тексты внизу, пока последний ребенок в вашем RelativeLayout - это LinearLayout, как показано выше.
Ответ 4
Если у вас все в порядке с RelativeLayout вместо Linear, то это будет трюк, я думаю:
<?xml version="1.0" encoding="utf-8"?>
<RelativeLayout android:id="@+id/LinearLayout1"
xmlns:android="http://schemas.android.com/apk/res/android"
android:orientation="vertical" android:layout_width="fill_parent"
android:layout_height="fill_parent">
<TextView android:layout_height="wrap_content"
android:layout_width="fill_parent" android:text="@string/hello"
android:id="@+id/TextView1" android:layout_above="@+id/TextView2"
android:layout_alignLeft="@+id/TextView2"></TextView>
<TextView android:layout_height="wrap_content"
android:layout_width="fill_parent" android:text="@string/hello"
android:id="@+id/TextView2" android:layout_alignParentBottom="true"> </TextView>
</RelativeLayout>
Ответ 5
Если вы пытаетесь сделать все три дочерних вида одинаковой высоты, затем измените высоту на "0", установите для android: weightSum из LinearLayout значение 3 и установите для android: layout_weight каждого вида значение 1.
Ответ 6
То же, что и Timmm, но вы можете использовать android:gravity="bottom"
для атрибута LinearLayout
вместо android:layout_gravity="bottom"
для каждого из TextView
.
Вот так:
<?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:gravity="bottom"
android:baselineAligned="false">
<TextView
android:layout_width="0dp"
android:layout_height="wrap_content"
android:text="your text 1......"
android:layout_weight="1"/>
<TextView
android:layout_width="0dp"
android:layout_height="wrap_content"
android:text="your text 2......"
android:layout_weight="1"/>
<TextView
android:layout_width="0dp"
android:layout_height="wrap_content"
android:text="your text 3......"
android:layout_weight="1"/>
</LinearLayout>