Android RelativeLayout и проблема с кнопками - PullRequest
0 голосов
/ 04 июля 2011

У меня есть макет, работающий как я хотел бы в портретном режиме.Однако он не отображается так, как хотелось бы в ландшафтном режиме:

Портретный режим

Пейзажный режим

ВотСхема XML-файла:

<RelativeLayout>

    <LinearLayout android:orientation="horizontal">
        <TextView />
        <TextView />
    </LinearLayout>

    <TextView />

    <LinearLayout android:orientation="vertical">

        <LinearLayout android:orientation="horizontal">

            <LinearLayout android:orientation="vertical">
                <TextView />
                <TextView />
            </LinearLayout>

            <LinearLayout android:orientation="vertical">
                <Spinner />
                <Spinner />
            </LinearLayout>

        </LinearLayout>

    </LinearLayout>

    <Button/>

</RelativeLayout>

А вот актуальный XML-файл

<?xml version="1.0" encoding="utf-8"?>

<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
    android:layout_width="fill_parent" android:layout_height="fill_parent">

    <LinearLayout android:id="@+id/departure_block"
        android:orientation="horizontal" android:layout_width="fill_parent"
        android:layout_height="wrap_content" android:layout_marginTop="40px">

        <TextView android:layout_width="wrap_content"
            android:layout_height="wrap_content" android:textSize="17sp"
            android:text="You are departing from " />

        <TextView android:id="@+id/editTextDepartureStation"
            android:layout_width="wrap_content" android:layout_height="wrap_content"
            android:text="" android:layout_weight="2" android:textSize="17sp" />
    </LinearLayout>

    <TextView android:id="@+id/info_block" android:layout_width="wrap_content"
        android:layout_height="wrap_content" android:textSize="17sp"
        android:layout_below="@id/departure_block" android:text="Please select remaining journey details: "
        android:layout_marginTop="40px" />

    <LinearLayout android:orientation="vertical"
        android:layout_width="fill_parent" android:layout_below="@id/info_block"
        android:layout_height="fill_parent">

        <!-- Labels and widgets -->
        <LinearLayout android:orientation="horizontal"
            android:layout_width="fill_parent" android:layout_height="wrap_content"
            android:layout_marginTop="20px">

            <!-- Labels -->
            <LinearLayout android:orientation="vertical"
                android:layout_width="fill_parent" android:layout_height="wrap_content"
                android:layout_weight="2" android:paddingBottom="10px">

                <TextView android:layout_width="wrap_content"
                    android:layout_height="70px" android:text="@string/destinationStation"
                    android:layout_weight="2" android:paddingTop="15px"
                    android:textSize="17sp" />

                <TextView android:layout_width="wrap_content"
                    android:layout_height="70px" android:text="@string/numTickets"
                    android:layout_weight="2" android:paddingTop="15px"
                    android:textSize="17sp" />
            </LinearLayout>
            <!-- End labels -->

            <!-- Widgets -->
            <LinearLayout android:orientation="vertical"
                android:layout_width="fill_parent" android:layout_height="wrap_content"
                android:layout_weight="1">

                <Spinner android:id="@+id/spinnerDestinationStation"
                    android:layout_width="fill_parent" android:layout_height="wrap_content"
                    android:prompt="@string/destination_prompt" android:layout_weight="1"
                    android:textSize="17sp" />


                <Spinner android:id="@+id/spinnerNumTickets"
                    android:layout_width="fill_parent" android:layout_height="wrap_content"
                    android:prompt="@string/numTickets_prompt" android:layout_weight="1"
                    android:textSize="17sp" />
            </LinearLayout>
            <!-- End widgets -->

        </LinearLayout>
        <!-- End labels and widgets -->

    </LinearLayout>


    <Button android:id="@+id/buttonPurchase" android:layout_width="fill_parent"
        android:layout_height="wrap_content" android:text="Purchase ticket"
        android:layout_weight="1" android:textSize="17sp" android:background="@drawable/custom_button"
        android:textColor="#ffffff" android:shadowColor="#000000"
        android:shadowRadius="1.5" android:layout_gravity="bottom"
        android:layout_alignParentBottom="true" android:shadowDx="1"
        android:shadowDy="1" android:layout_margin="10px" />


</RelativeLayout>

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

Я бы хотел, чтобы любая прокрутка или ScrollView инкапсулировали кнопку.Это не проблема, если кнопка появляется в нижней части дисплея - до тех пор, пока к ней можно получить доступ с помощью прокрутки.Это то, чего я изо всех сил пытался достичь.

Кто-нибудь может помочь?

Большое спасибо.

Ответы [ 3 ]

2 голосов
/ 04 июля 2011

Ваш макет слишком велик для экрана, поэтому вам придется обернуть info_block в ScrollView и выровнять его по верху, а также по его нижней части к верхней части кнопки.

Это означает, что вам нужно определить кнопку до информационного блока, чтобы вы могли выровнять нижнюю часть информационного блока по верху кнопки.

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

1 голос
/ 04 июля 2011

Может быть, лучшим вариантом было бы сделать прокрутку с относительной раскладкой способной, по-моему, вызывать?Таким образом, пользователь может использовать свой палец для перемещения всего макета вверх и вниз.

0 голосов
/ 04 июля 2011

Мне придется проверить завтра, но fillViewport, кажется, является атрибутом ScrollView, который я хочу.Объяснено в: Удобный трюк ScrollView .

Отредактированный, чтобы добавить это, решил мою проблему.Две важные вещи:

  1. Чтобы использовать fillViewport = "true" в ScrollView, это гарантирует, что дочерний элемент расширяется для заполнения дисплея.Одного этого будет недостаточно, необходимо убедиться в следующем:

  2. Последний элемент перед Кнопка имеет android: layout_weight = "1.0", чтобы обеспечить ее заполнениепространство, созданное ScrollView, имеющее fillViewport = "true".

...