Выравнивание текстовых представлений по левому и правому краям в макете Android - PullRequest
144 голосов
/ 20 января 2010

Я начинаю с 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>

Ответы [ 8 ]

272 голосов
/ 20 января 2010

Используйте 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 отражает настройки текста, а также плотность экрана, поэтому они обычно используются только для определения размера текстовых элементов.

84 голосов
/ 20 января 2010

Вы можете использовать свойство gravity для "плавания" видов.

<?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>
6 голосов
/ 07 марта 2018

Это можно сделать с помощью LinearLayout (меньше накладных расходов и больше контроля, чем у параметра «Относительная компоновка»). Дайте второму виду оставшееся пространство, чтобы 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> 

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

Отрегулируйте веса по мере необходимости. Относительная компоновка не позволит вам установить процентный вес, как этот, только фиксированный дп одного из представлений

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>
6 голосов
/ 03 марта 2015

Даже с подсказкой Роллина, ответ Дэйва Уэбба мне не помог.Текст справа 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".

Надеюсь, это кому-нибудь поможет!

4 голосов
/ 22 января 2015

<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" />

0 голосов
/ 18 мая 2019

Если вы хотите, чтобы левый и правый элементы переносили содержимое, но имели средний пробел

<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>
0 голосов
/ 07 мая 2018

Ответ Дэйва Уэбба сработал для меня.Спасибо!Вот мой код, надеюсь, это кому-нибудь поможет!

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

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

0 голосов
/ 25 апреля 2018

Есть много других способов сделать это, я бы сделал что-то вроде этого.

<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>
Добро пожаловать на сайт PullRequest, где вы можете задавать вопросы и получать ответы от других членов сообщества.
...