Выравнивание текстовых изображений на левом и правом краях в макете Android
Я начинаю работу с Android. У меня возникли проблемы с получением простой компоновки.
Я хотел бы использовать LinearLayout
для размещения двух TextViews
в одной строке. Один TextView
с левой стороны, другой с правой стороны (аналогично float: left, float: right в CSS).
Возможно ли это, или мне нужно использовать другой ViewGroup
или другое вложение макета для его выполнения?
Вот что я до сих пор:
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="fill_parent" android:layout_height="fill_parent"
android:orientation="horizontal" android:padding="10sp">
<TextView android:id="@+id/mytextview1" android:layout_height="wrap_content" android:text="somestringontheleftSomestring" android:layout_width="wrap_content"/>
<TextView android:id="@+id/mytextview2" android:layout_height="wrap_content" android:ellipsize="end"
android:text="somestringontheright" android:layout_width="wrap_content"/>
</LinearLayout>
Ответы
Ответ 1
Используйте RelativeLayout
с layout_alignParentLeft
и layout_alignParentRight
:
<RelativeLayout
xmlns:android="http://schemas.android.com/apk/res/android"
android:id="@+id/RelativeLayout01"
android:layout_width="fill_parent"
android:layout_height="fill_parent"
android:padding="10dp">
<TextView
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_alignParentLeft="true"
android:id="@+id/mytextview1"/>
<TextView
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_alignParentRight="true"
android:id="@+id/mytextview2"/>
</RelativeLayout>
Кроме того, вероятно, вы должны использовать dip
(или dp
), а не sp
в своем макете. sp
отражают настройки текста, а также плотность экрана, поэтому они обычно предназначены только для выбора текстовых элементов.
Ответ 2
Вы можете использовать свойство gravity для просмотра "float".
<?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">
<LinearLayout
android:layout_width="fill_parent"
android:layout_height="fill_parent"
android:gravity="center_vertical|center_horizontal"
android:orientation="horizontal">
<TextView
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:gravity="left"
android:layout_weight="1"
android:text="Left Aligned"
/>
<TextView
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:gravity="right"
android:layout_weight="1"
android:text="Right Aligned"
/>
</LinearLayout>
</LinearLayout>
Ответ 3
Это можно сделать с помощью LinearLayout
(меньше накладных расходов и большего контроля, чем опция Relative Layout). Дайте второму виду оставшееся пространство, чтобы gravity
могла работать. Протестировано обратно к API 16.
![Proof]()
<LinearLayout
android:layout_width="match_parent"
android:layout_height="match_parent">
<TextView
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="Aligned left" />
<TextView
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:gravity="end"
android:text="Aligned right" />
</LinearLayout>
Если вы хотите ограничить размер первого текстового вида, сделайте следующее:
При необходимости отрегулируйте вес. Относительная компоновка не позволит вам установить процентный вес, как это, только фиксированный dp одного из видов
![Proof 2]()
<LinearLayout
android:layout_width="match_parent"
android:layout_height="match_parent">
<TextView
android:layout_width="0dp"
android:layout_weight="1"
android:layout_height="wrap_content"
android:text="Aligned left but too long and would squash the other view" />
<TextView
android:layout_width="0dp"
android:layout_weight="1"
android:layout_height="wrap_content"
android:gravity="end"
android:text="Aligned right" />
</LinearLayout>
Ответ 4
Даже с подсказкой Rollin_s, ответ Дейва Уэбба не работал у меня. Текст в правом TextView
по-прежнему перекрывал текст в левой части TextView
.
В конце концов я получил такое поведение, которое я хотел:
<RelativeLayout
xmlns:android="http://schemas.android.com/apk/res/android"
android:id="@+id/RelativeLayout01"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:padding="10dp">
<TextView
android:id="@+id/mytextview1"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_alignParentLeft="true" />
<TextView
android:id="@+id/mytextview2"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:layout_toRightOf="@id/mytextview1"
android:gravity="right"/>
</RelativeLayout>
Обратите внимание, что mytextview2 имеет "android:layout_width"
как "match_parent"
.
Надеюсь, это поможет кому-то!
Ответ 5
<TextView
android:layout_width="0dp"
android:layout_height="wrap_content"
android:layout_weight="1"
android:text="Hello world" />
<View
android:layout_width="0dp"
android:layout_height="match_parent"
android:layout_weight="1" />
<TextView
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="Gud bye" />
Ответ 6
Есть много других способов сделать это, я бы сделал что-то подобное.
<RelativeLayout
xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="match_parent"
android:layout_height="wrap_content">
<TextView
android:id="@+id/textRight"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_alignParentRight="true"
android:layout_marginTop="30dp"
android:text="YOUR TEXT ON THE RIGHT"
android:textSize="16sp"
android:textStyle="italic" />
<TextView
android:id="@+id/textLeft"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_alignParentLeft="true"
android:layout_marginTop="30dp"
android:text="YOUR TEXT ON THE LEFT"
android:textSize="16sp" />
</RelativeLayout>
Ответ 7
Ответ Дейва Уэбба действительно сработал для меня. Спасибо! Вот мой код, надеюсь, это поможет кому-то!
<RelativeLayout
android:background="#FFFFFF"
android:layout_width="match_parent"
android:minHeight="30dp"
android:layout_height="wrap_content">
<TextView
android:height="25dp"
android:layout_width="wrap_content"
android:layout_marginLeft="20dp"
android:text="ABA Type"
android:padding="3dip"
android:layout_gravity="center_vertical"
android:gravity="left|center_vertical"
android:layout_height="match_parent" />
<TextView
android:background="@color/blue"
android:minWidth="30px"
android:minHeight="30px"
android:layout_column="1"
android:id="@+id/txtABAType"
android:singleLine="false"
android:layout_gravity="center_vertical"
android:layout_weight="1"
android:layout_height="wrap_content"
android:layout_alignParentRight="true"
android:layout_marginRight="20dp"
android:layout_width="wrap_content" />
</RelativeLayout>
Изображение: Изображение
Ответ 8
В случае, если вы хотите, чтобы левый и правый элементы переносили содержимое, но имели средний пробел
<LinearLayout
android:orientation="horizontal"
android:layout_width="match_parent"
android:layout_height="wrap_content">
<TextView
android:layout_width="wrap_content"
android:layout_height="wrap_content"/>
<Space
android:layout_width="0dp"
android:layout_height="match_parent"
android:layout_weight="1"/>
<Button
android:layout_width="wrap_content"
android:layout_height="wrap_content"/>
</LinearLayout>
Ответ 9
![enter image description here]()
Этот код разделит контроль на две равные стороны.
<LinearLayout
android:orientation="horizontal"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:id="@+id/linearLayout">
<TextView
android:text = "Left Side"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:layout_weight = "1"
android:id = "@+id/txtLeft"/>
<TextView android:text = "Right Side"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:layout_weight = "1"
android:id = "@+id/txtRight"/>
</LinearLayout>