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

Добавление представления в начало макета внутри прокрутки

Итак, мой макет выглядит в основном следующим образом:

<ScrollView>
    <RelativeLayout>
        <BunchOfViews/>
        <ImageView android:layout_alignParentBottom="true"/>
    </RelativeLayout>
</ScrollView>

У меня есть ScrollView, поэтому все макеты всегда видны независимо от высоты экрана. Проблема в том, что на очень высоком экране я все еще хочу, чтобы мой ImageView был внизу. Однако у дочернего элемента ScrollView нет определенного дна. View находится в верхней части макета. Как я могу решить эту проблему аккуратным способом?

4b9b3361

Ответ 1

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

Мой взлом заключался в том, чтобы добавить фиктивный linearlayout в нижней части scrollview с fill_parent, чтобы занять всю комнату и заставить scrollview заполнить экран. Затем добавьте какой-нибудь компонент, который я хочу для этого linearlayout.

Вот один из моих макетов, который делает это:

<ScrollView
    android:layout_width="fill_parent"
    android:layout_height="fill_parent"
    android:layout_weight="1"
    android:fillViewport="true" >

    <RelativeLayout
        android:layout_width="fill_parent"
        android:layout_height="fill_parent"
        android:layout_marginTop="15px" >

        <!-- bunch of components here -->

        <LinearLayout
            android:layout_width="fill_parent"
            android:layout_height="fill_parent"
            android:layout_below="@+id/spinner"
            android:layout_marginTop="5px"
            android:gravity="center_horizontal|bottom"
            android:paddingTop="2px" >

            <Button
                android:layout_width="wrap_content"
                android:layout_height="wrap_content"
                android:paddingLeft="20px"
                android:paddingRight="20px"
                android:text="Delete" />
        </LinearLayout>
    </RelativeLayout>
</ScrollView>

Ответ 2

У меня была такая же проблема и я нашел эту страницу:

http://www.curious-creature.org/2010/08/15/scrollviews-handy-trick/

В принципе, для параметра ScrollView android:fillViewport установлено значение true, что позволит дочернему представлению расширяться до той же высоты, что и сам ScrollView, заполняя пробел. Затем вам нужно просто установить один из дочерних элементов управления layout_height на fill_parent и layout_weight на 1, заставив этот элемент управления "spring" заполнить пустое пространство.

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

Мой последний XML выглядит примерно так:

<ScrollView
    android:layout_width="fill_parent"
    android:layout_height="fill_parent"
    android:fillViewport="true">
    <LinearLayout
        android:orientation="vertical"
        android:layout_height="wrap_content">
        <LinearLayout
            android:layout_height="fill_parent"
            android:layout_weight="1">
            <!-- this expands to fill the empty space if needed -->
        </LinearLayout>

        <!-- this sits at the bottom of the ScrollView,
        getting pushed out of view if the ScrollView's
        content is tall enough -->
        <ImageView
            android:layout_height="wrap_content"
            android:src="@drawable/footer_image">
        </ImageView>
    </LinearLayout>
</ScrollView>

Ответ 3

кажется, что linearlayout не требуется, все, что важно, это fillViewPort. вы можете просто использовать

    <Button
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:layout_alignBottomParent="true">

теперь, когда вы указали, что значение relativelayout будет как минимум размером экрана.

Ответ 4

его работа для меня отлично андроида: fillViewport = "true"

Ответ 5

Joel Malone отвечает Добавление представления в начало макета внутри прокрутки > делает этот трюк. Мое решение почти то же самое, за исключением того, что я использую виджет Space, чтобы выполнить работу по заполнению высоты отдыха внутри родительского макета. Вот так:

<ScrollView
    android:layout_width="match_parent"
    android:layout_height="match_parent
    android:fillViewport="true"
    >
    <LinearLayout
        android:orientation="vertical"
        android:layout_height="wrap_content"
        >
        <android.support.v4.widget.Space
            android:layout_height="match_parent"
            android:layout_weight="1"
            />
    <ImageView
        android:layout_height="wrap_content"
        android:src="@drawable/footer_image"
        />
    </LinearLayout>
</ScrollView>

Внимание:

  • fill_parent в других ответах отмечается как устаревшее в течение длительного времени;
  • Сравните с пустым LinearLayout, чтобы заполнить остальную часть родительского макета, я думаю, что Space гораздо более уместен (он предназначен для выполнения этой работы.)
  • Наконец, не забудьте этот важный атрибут в начале ScrollView: android:fillViewport="true". Они вместе делают этот трюк.

Ответ 6

По вашему мнению, что вы хотите быть на дне, используйте андроид: gravity = "bottom"

Ответ 7

От: http://code.google.com/p/k9mail/source/browse/k9mail/trunk/res/layout/account_setup_basics.xml?r=1314

Это должно помочь вам:

<RelativeLayout
        android:layout_marginTop="-45dip" 
        android:padding="0dip"
        android:layout_alignParentBottom="true"
        android:gravity="bottom|right" 
        android:background="@android:drawable/bottom_bar"
        android:layout_height="fill_parent"
        android:layout_width="fill_parent">
        <Button
            android:id="@+id/manual_setup"
            android:text="@string/account_setup_basics_manual_setup_action"
            android:minWidth="@dimen/button_minWidth"
            android:layout_height="wrap_content"
            android:layout_width="wrap_content"
            android:layout_marginBottom="-4dip" 
            android:layout_alignParentLeft="true"
            android:layout_centerVertical="false" 
            />
        <Button
            android:id="@+id/next"
            android:text="@string/next_action"
            android:minWidth="@dimen/button_minWidth"
            android:layout_height="wrap_content"
            android:layout_width="wrap_content"
            android:drawableRight="@drawable/button_indicator_next"
            android:layout_marginBottom="-4dip" 
            android:layout_alignParentRight="true"
            android:layout_centerVertical="false" 
            />
    </RelativeLayout>

Ответ 8

ScrollView view = new ScrollView( this );
ScrollView.LayoutParams lps = new FrameLayout.LayoutParams( FILL_PARENT, FILL_PARENT, Gravity.CENTER );
LinearLayout layout = new LinearLayout( this );
// what ever you want in the Layout 
view.addView( layout, lps );