Як правильно вирівняти віджет у горизонтальній лінійній версії Android?


205

Це код, який я використовую, і він не працює:

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

    <TextView android:text="TextView" android:id="@+id/textView1"
        android:layout_width="wrap_content" 
        android:layout_height="wrap_content"
        android:gravity="right">
    </TextView>

</LinearLayout>

Відповіді:


418

Спробуйте додати порожній Viewвсередині горизонталі LinearLayoutперед елементом, який ви хочете бачити право, наприклад:

<LinearLayout
    android:layout_width="match_parent"
    android:layout_height="wrap_content" >

    <View
        android:layout_width="0dp"
        android:layout_height="0dp"
        android:layout_weight="1" />                

    <Button
        android:layout_width="wrap_content"
        android:layout_height="wrap_content" />

</LinearLayout>

11
Це працює! Але хто може пояснити, чому? Я не міг повністю зрозуміти.
— GMsoF

28
Empty View намагається зайняти максимальну кількість місця, залишаючи місце для кнопки.
— alcsan

14
Поки що це єдине, що працює для мене, намагаючись мати кілька кнопок зліва та одну остаточну кнопку праворуч. Але мені здається, що це хак. Чи є "правильний" спосіб це зробити?
— IcedDante

8
Це круто! Але чому гравітація = "правильно" не працює таким чином з самого початку? Для чого потрібна допомога з цього іншого погляду? І як це "правильно", якщо його немає, без зайвого погляду?
— afrish

1
Це не працює в сітчастому макеті - немає порожнього місця. Рішення шерифа ель-Катіба працює.
— cdonner

119

Не змінюйте гравітацію LinearLayout на "правильну", якщо ви не хочете, щоб все було правильно.

Спробуйте:

  1. Змініть ширину TextView наfill_parent
  2. Змініть гравітацію TextView наright

Код:

    <TextView 
              android:text="TextView" 
              android:id="@+id/textView1"
              android:layout_width="fill_parent"
              android:layout_height="wrap_content"   
              android:gravity="right">
    </TextView>

1
спасибі за це - саме ширина fill_parent відкинула мене
— dldnh

2
Чи спроектовано лінійне планування для досягнення цього? Чи не слід просто використовувати відносний макет, щоб досягти цього? Невже це рішення не є злому?
— користувач2635088

це не буде працювати, якщо у вас є кілька елементів TextView в LinearLayout. Дивіться відповідь від @alcsan
— Фелікс

Це має бути прийнятою відповіддю. Цей підхід не використовує додаткових подань, і що ще важливіше, він не використовує layout_weight, що значно знижує продуктивність.
— Sermilion

android:layout_weight = "1"пліч-о-пліч android:gravity="right", повинні зробити трюк.
— Василіс

63

Як доповнення до відповіді alcsan, ви можете використовувати, Spaceоскільки API 14 (Android 4.0 ICE_CREAM_SANDWICH) тут можна документувати .

Простір - це легкий підклас View, який може бути використаний для створення прогалин між компонентами у загальних цілях планування.

<?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="match_parent" 
    android:orientation="horizontal" >

    <Space
        android:layout_width="0dp"
        android:layout_height="0dp"
        android:layout_weight="1" />

    <TextView
        android:layout_width="wrap_content" 
        android:layout_height="wrap_content"
        android:text="TextView"
        android:gravity="right" />

</LinearLayout>

Для додатків, що підтримують рівні API до 14 років, існує android.support.v4.widget.SpaceAndroid-бібліотека підтримки r22.1.0.


Важливо те, що вам потрібно встановити layout_weight = "1"
— code4j

Працює чудово! Зберігається ширина кожного елемента.
— phatmann

Це працює. Ого, потворність Android ніколи не перестає дивувати мене
— Кріс Нев,

31

З лінійним макетом

<LinearLayout
        android:layout_width="fill_parent"
        android:layout_height="wrap_content"
        android:background="@drawable/select_car_book_tabbar"
        android:gravity="right" >

        <ImageView
            android:layout_width="wrap_content"
            android:layout_height="wrap_content"
            android:layout_gravity="center_vertical"
            android:src="@drawable/my_booking_icon" />
    </LinearLayout>

введіть тут опис зображення

з FrameLayout

<FrameLayout
        android:layout_width="fill_parent"
        android:layout_height="wrap_content"
        android:background="@drawable/select_car_book_tabbar">

        <ImageView
            android:layout_width="wrap_content"
            android:layout_height="wrap_content"
            android:layout_gravity="center_vertical|right"
            android:src="@drawable/my_booking_icon" />
    </FrameLayout>

з RelativeLayout

<RelativeLayout
        android:layout_width="fill_parent"
        android:layout_height="wrap_content"
        android:background="@drawable/select_car_book_tabbar">

        <ImageView
            android:layout_width="wrap_content"
            android:layout_height="wrap_content"
            android:layout_alignParentRight="true"
            android:layout_centerInParent="true"
            android:src="@drawable/my_booking_icon" />
    </RelativeLayout>

21

встановлення перегляду layout_weight="1"зробило б свою задачу!

<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:orientation="horizontal">

<TextView
    android:id="@+id/textView1"
    android:layout_width="fill_parent"
    android:layout_height="wrap_content"
    android:layout_weight="1" />

<RadioButton
    android:id="@+id/radioButton1"
    android:layout_width="wrap_content"
    android:layout_height="wrap_content"/>


2
Таке просте рішення +1
— Алекс

1
Якщо хтось все ще шукає, це правильне рішення :)
— passatgt

Це магія! Як ви це дізналися?
— andreikashin

@andreikashin, Подумайте про те, як це допомогло. Дякую.
— Саад Махмуд

13

Додати android:gravity="right"до LinearLayout. Припустимо, що TextViewмаєlayout_width="wrap_content"


2
Він спеціально сказав вирівняти один компонент всередині LinearLayout. Не сама лінійна компоновка: сам макет встановлений на fill_parent.
— RichieHH


4

Я це зробив найпростішим способом:

Просто візьміть один відносний макет і поставте в нього подання дитини , яке ви хочете розмістити в правій частині.

    <LinearLayout
        android:id="@+id/llMain"
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:background="#f5f4f4"
        android:gravity="center_vertical"
        android:orientation="horizontal"
        android:paddingBottom="20dp"
        android:paddingLeft="15dp"
        android:paddingRight="15dp"
        android:paddingTop="20dp">

        <ImageView
            android:id="@+id/ivOne"
            android:layout_width="wrap_content"
            android:layout_height="wrap_content"
            android:src="@drawable/ic_launcher" />


        <TextView
            android:id="@+id/txtOne"
            android:layout_width="wrap_content"
            android:layout_height="wrap_content"
            android:layout_marginLeft="20dp"
            android:text="Hiren"
            android:textAppearance="@android:style/TextAppearance.Medium"
            android:textColor="@android:color/black" />

        <RelativeLayout
            android:id="@+id/rlRight"
            android:layout_width="match_parent"
            android:layout_height="wrap_content"
            android:gravity="right">


            <ImageView
                android:id="@+id/ivRight"
                android:layout_width="wrap_content"
                android:layout_height="wrap_content"
                android:padding="5dp"
                android:src="@drawable/ic_launcher" />

        </RelativeLayout>
    </LinearLayout>

Сподіваюся, це допоможе вам.


3

Ви повинні використовувати RelativeLayout і просто перетягнути їх, поки це не виглядає добре :)

    <ImageView
        android:id="@+id/button_info"
        android:layout_width="30dp"
        android:layout_height="wrap_content"
        android:layout_alignParentRight="true"
        android:layout_alignParentTop="true"
        android:layout_marginRight="10dp"
        android:contentDescription="@string/pizza"
        android:src="@drawable/header_info_button" />

</RelativeLayout>

2
"перетягнути їх" не рекомендується для екрана з декількома роздільними можливостями
— Мойсей Априко

3

linear layoutз, layout_width="fill_parent"а також віджет з той же layout width+ gravity as rightвирівняв би його праворуч.

Я використовую 2 TextViewс у наступному прикладі, topicTitleзліва та topicQuestionsсправа.

<?xml version="1.0" encoding="utf-8"?>
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
    android:layout_width="match_parent"
    android:layout_height="match_parent">

    <LinearLayout
        android:layout_width="fill_parent"
        android:layout_height="wrap_content"
        android:paddingLeft="20dp"
        android:orientation="horizontal">

    <TextView
        android:id="@+id/topicTitle"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:textSize="18sp"
        android:textStyle="bold" />

    <TextView
        android:id="@+id/topicQuestions"
        android:layout_width="fill_parent"
        android:layout_height="wrap_content"
        android:gravity="right"
        android:textSize="18sp"
        android:textStyle="bold" />
    </LinearLayout>

</RelativeLayout>

Вихідні дані


2

Спробуйте змінити layout_width на android:layout_width="match_parent"тому, що gravity:"right"вирівнює текст всередині layout_width, і якщо ви виберете обгортковий вміст, він не має куди йти, але якщо ви вибрали збіг батьків, він може перейти праворуч.


2

Не потрібно використовувати додатковий вигляд або елемент:

// що так легко і просто

<LinearLayout
  android:layout_width="match_parent"
  android:layout_height="wrap_content"
  android:orientation="horizontal"
>

// це ліве вирівнювання

<TextView
      android:layout_width="wrap_content"
      android:layout_height="wrap_content"
      android:text="No. of Travellers"
      android:textColor="#000000"
      android:layout_weight="1"
      android:textStyle="bold"
      android:textAlignment="textStart"
      android:gravity="start" />

// це правильне вирівнювання

<TextView
      android:layout_width="wrap_content"
      android:layout_height="wrap_content"
      android:text="Done"
      android:textStyle="bold"
      android:textColor="@color/colorPrimary"
      android:layout_weight="1"
      android:textAlignment="textEnd"
      android:gravity="end" />

</LinearLayout>

0

У випадку з TextView:

<TextView 
    android:text="TextView" 
    android:id="@+id/textView"
    android:layout_width="fill_parent"
    android:layout_height="wrap_content"   
    android:gravity="right"
    android:textAlignment="gravity">    
</TextView>

0

Додавання перегляду трохи складно, і воно охоплює всю ширину екрана так:

<LinearLayout
android:layout_width="match_parent"
android:layout_height="wrap_content" >

<View
    android:layout_width="0dp"
    android:layout_height="0dp"
    android:layout_weight="1" />                

<Button
    android:layout_width="wrap_content"
    android:layout_height="wrap_content" />

Спробуйте ввести цей код:

<LinearLayout
    android:layout_width="wrap_content"
    android:layout_height="wrap_content"
    android:layout_gravity="right"
    >

    <Button
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:text="Create Account"/>

</LinearLayout>

-1

Ось зразок. ключовим для організації є наступне

android:layout_width="0dp"
android:layout_weight="1"

Повний код

<?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:padding="5dp">

    <TextView
        android:id="@+id/categoryName"
        android:layout_width="0dp"
        android:layout_height="wrap_content"
        android:layout_weight="1"
        android:text="abcd" />

    <TextView
        android:id="@+id/spareName"
        android:layout_width="0dp"
        android:layout_height="wrap_content"
        android:layout_weight="1"
        android:text="efgh" />

</LinearLayout>

введіть тут опис зображення


-1

Використовуйте match_parent і gravity, щоб встановити текст 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="match_parent"
    android:orientation="horizontal">

    <TextView android:text="TextView" android:id="@+id/textView1"
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:gravity="right">
    </TextView>

</LinearLayout>

-2

Спробуйте це..

<?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:gravity="right" >



    <TextView android:text="TextView" android:id="@+id/textView1"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content">
    </TextView>

</LinearLayout>
Використовуючи наш веб-сайт, ви визнаєте, що прочитали та зрозуміли наші Політику щодо файлів cookie та Політику конфіденційності.
Licensed under cc by-sa 3.0 with attribution required.