Подтвердить что ты не робот

RelativeLayout: align Выравнивание по горизонтали или по вертикали относительно другого вида

Можно ли выровнять представление в XML в горизонтальной или вертикальной ориентации RelativeLayout в соответствии с другим уже существующим представлением.

Например: скажем, что-то вроде этого:

enter image description here

Второй текстовый вид должен отображаться в центре ниже первого текстового вида:

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

    <TextView
        android:id="@+id/textView"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:layout_alignParentLeft="true"
        android:layout_marginLeft="72dp"
        android:text="dynamic text" />

    <TextView
        android:id="@+id/second"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:layout_below="@id/textView"
        android:layout_marginLeft="43dp" <!-- Is there a rule to center it? -->
        android:text="centered below text 1" />

</RelativeLayout>

Можно ли реализовать что-то подобное в XML? Есть ли правило, которое я пропустил? Я не хочу вычислять позицию программно

4b9b3361

Ответ 1

Используйте отдельный родительский макет для этих представлений и добавьте его в свой основной макет (может содержать другие вещи, если есть)

<?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="wrap_content"
         android:layout_height="wrap_content"
         android:orientation="vertical"
         android:gravity="center"
         android:layout_marginLeft = "30dp">
        <TextView
            android:id="@+id/textView"
            android:layout_width="wrap_content"
            android:layout_height="wrap_content"
            android:text="dynamic text" />

        <TextView
            android:id="@+id/second"
            android:layout_width="wrap_content"
            android:layout_height="wrap_content"
            android:text="centered below text 1" />
    </LinearLayout>
...
...
other veiws go here
...

</RelativeLayout>

Ответ 2

У меня гораздо лучшее решение, чем принятое. НЕТ ДОПОЛНИТЕЛЬНОГО ГНЕЗДА! Вы можете сделать это, объединив два атрибута на более мелком представлении. если вы центрируете по горизонтали, вы можете использовать как align_start, так и align_end для большего просмотра. Убедитесь, что гравитация текста центрирована с помощью "android: gravity =" center ". Для вертикального выравнивания используйте как align_top, так и align_bottom ниже, это модифицированная реализация вашего макета.

<?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"
android:paddingLeft="43dp" >

<TextView
    android:id="@+id/textView"
    android:layout_width="wrap_content"
    android:layout_height="wrap_content"
    android:layout_alignStart="@+id/second"
    android:layout_alignEnd="@+id/second"
    android:gravity="center"
    android:text="dynamic text" />

<TextView
    android:id="@+id/second"
    android:layout_width="wrap_content"
    android:layout_height="wrap_content"
    android:layout_below="@id/textView"
    android:gravity="center"
    android:text="centered below text 1" />

</RelativeLayout>

Нет необходимости в ненужной вложенности, как принятый ответ.

Ответ 3

Используйте следующие действия, которые вам подходят

    android:layout_centerHorizontal="true"
    android:layout_centerInParent="true"    
    android:layout_centerVertical="true"    

Ответ 4

Сделайте это →

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

    <TextView
        android:id="@+id/textView"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:layout_centerHorizontal="true"
        android:text="dynamic text" />

    <TextView
        android:id="@+id/second"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:layout_below="@+id/textView"
        android:layout_centerHorizontal="true" <!-- Is there a rule to center it? -->
        android:text="centered below text 1" />

</RelativeLayout>

Ответ 5

Я нашел решение: Оберните содержимое в другое RelativeLayout, а затем вы можете разместить этот LayoutWrapper везде, где хотите:

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

    <RelativeLayout
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:layout_alignParentLeft="true"
        android:layout_alignParentTop="true"
        android:layout_marginLeft="58dp"
        android:layout_marginTop="58dp" >

        <TextView
            android:id="@+id/textView"
            android:layout_width="wrap_content"
            android:layout_height="wrap_content"
            android:layout_alignParentTop="true"
            android:layout_centerInParent="true"
            android:text="dynamic text" />

        <TextView
            android:id="@+id/second"
            android:layout_width="wrap_content"
            android:layout_height="wrap_content"
            android:layout_below="@+id/textView"
            android:layout_centerInParent="true"
            android:text="centered below text 1" />
    </RelativeLayout>

</RelativeLayout>

Ответ 6

Правильное решение - использовать ConstraintLayout

Я попытался выровнять текстовое изображение горизонтально под кнопкой в ​​RelativeLayout, но это было невозможно, так как align_bottom и layout_below не играли хорошо вместе. Наконец, я взял constraintLayout и попробовал ту же логику, и это сработало как шарм. вот код ниже.

<android.support.constraint.ConstraintLayout 
xmlns:app="http://schemas.android.com/apk/res-auto"
xmlns:tools="http://schemas.android.com/tools"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:clipChildren="false"
xmlns:android="http://schemas.android.com/apk/res/android">

<Button
    android:id="@+id/episode_recording_header_stop"
    android:layout_width="wrap_content"
    android:layout_height="wrap_content"
    android:background="@mipmap/ic_launcher"
    app:layout_constraintBottom_toBottomOf="parent"
    app:layout_constraintEnd_toEndOf="parent"
    app:layout_constraintStart_toStartOf="parent"
    app:layout_constraintTop_toTopOf="parent"
    app:layout_constraintVertical_bias="0.399" />


<TextView
    android:id="@+id/button_selected_text"
    android:layout_width="wrap_content"
    android:layout_height="wrap_content"
    android:layout_margin="8dp"
    android:textAlignment="center"
    android:textColor="@android:color/black"
    android:textSize="12sp"
    android:text="text which is exactly center aligned w.r.t the Button above"
    app:layout_constraintEnd_toEndOf="@+id/episode_recording_header_stop"
   app:layout_constraintStart_toStartOf="@+id/episode_recording_header_stop"
    app:layout_constraintTop_toBottomOf="@+id/episode_recording_header_stop" 
    />

</android.support.constraint.ConstraintLayout>

Окончательный вывод приведен ниже

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