Содержимое по центру в режиме прокрутки

Я хочу центрировать свой LinearLayout в ScrollView. Когда высота LinearLayout мала, он правильно центрируется (см. изображение №1), но когда высота LinearLayout больше высоты экрана, он ведет себя странно. Я не вижу верхнюю часть LinearLayout (см. изображение № 2), а внизу ScrollView есть огромные отступы. Я не знаю, что здесь происходит. Когда в LinearLayout много контента, весь экран должен выглядеть как на изображении №3.

изображение №1
изображение №2
изображение №3

Вот мой файл макета:

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

                <LinearLayout
                    android:layout_width="match_parent"
                    android:layout_height="wrap_content"
                    android:layout_gravity="center_vertical"
                    android:layout_margin="28dp"
                    android:background="#ffffff"
                    android:orientation="vertical"
                    android:paddingBottom="40dp"
                    android:paddingLeft="20dp"
                    android:paddingRight="20dp"
                    android:paddingTop="40dp" >

                    <ImageView
                        android:layout_width="wrap_content"
                        android:layout_height="wrap_content"
                        android:layout_marginBottom="16dp"
                        android:src="@drawable/ic_launcher" />

                    <TextView
                        android:id="@+id/tip_title"
                        android:layout_width="wrap_content"
                        android:layout_height="wrap_content"
                        android:layout_marginBottom="12dp"
                        android:text="Title"
                        android:textColor="@color/orange_text"
                        android:textSize="@dimen/font_size_medium" />

                    <TextView
                        android:id="@+id/tip_description"
                        android:layout_width="wrap_content"
                        android:layout_height="wrap_content"
                        android:text="Description description..."
                        android:textSize="@dimen/font_size_small" />
                </LinearLayout>

            </ScrollView>

person Egis    schedule 23.10.2013    source источник
comment
установите layout_gravity = center, чтобы представления были отцентрированы   -  person Muhammad Babar    schedule 23.10.2013
comment
Вы, сэр, заслуживаете голоса за "Увеличь темп, подними темп, подтолкни темп, подтолкнуй темп"   -  person Nursultan Talapbekov    schedule 03.04.2015


Ответы (8)


Вы можете использовать android:fillViewport="true" для центрирования содержимого. Что-то вроде этого:

<ScrollView xmlns:android="http://schemas.android.com/apk/res/android"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    android:fillViewport="true">
        <!-- content -->
</ScrollView>
person yaircarreno    schedule 12.11.2015
comment
Это лучшее решение. Это не связано с созданием бесполезного LinearLayout в иерархии. - person Stephane Mathis; 13.10.2016
comment
Отлично! layout_gravity по центру в LinearLayout заставил его скрыть содержимое под панелью инструментов. Этот сработал! - person kirtan403; 06.11.2016
comment
Это не работает. Я только что сделал это, и кнопки выравниваются по левому краю, как будто ничего не произошло. - person Yokhen; 13.09.2018
comment
Почему это сработает? Содержимое по-прежнему будет за пределами границ, если гравитация установлена ​​​​в центре - person Boldijar Paul; 30.12.2020

Вы должны использовать внешний горизонтальный LinearLayout. У меня работает в такой же ситуации.

<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
        android:layout_width="match_parent"
        android:layout_height="match_parent"
        android:gravity="center"
        android:orientation="horizontal" >
    <ScrollView
            android:layout_width="match_parent"
            android:layout_height="wrap_content"
            android:orientation="vertical" >
        <LinearLayout
                android:orientation="vertical"
                android:layout_width="match_parent"
                android:layout_height="wrap_content"
                android:gravity="center_horizontal" >
            <TextView
                    android:text="@string/your_text"
                    android:layout_width="wrap_content"
                    android:layout_height="wrap_content" />
        </LinearLayout>
    </ScrollView>
</LinearLayout>
person Vladimir Petrakovich    schedule 11.12.2013

И вот как вы центрируете представление внутри ConstraintLayout

<?xml version="1.0" encoding="utf-8"?>
<androidx.constraintlayout.widget.ConstraintLayout xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:app="http://schemas.android.com/apk/res-auto"
    android:layout_width="match_parent"
    android:layout_height="match_parent">

    <androidx.appcompat.widget.Toolbar
        android:id="@+id/toolbar"
        android:layout_width="match_parent"
        android:layout_height="?attr/actionBarSize"
        android:background="#86c2e1"
        android:elevation="4dp"
        app:layout_constraintTop_toTopOf="parent"
        app:title="Toolbar" />

    <ScrollView
        android:layout_width="match_parent"
        android:layout_height="0dp"
        android:background="#eda200"
        app:layout_constraintBottom_toBottomOf="parent"
        app:layout_constraintHeight_default="wrap"
        app:layout_constraintTop_toBottomOf="@+id/toolbar"
        app:layout_constraintVertical_bias="0.5">

        <TextView
            android:layout_width="match_parent"
            android:layout_height="wrap_content"
            android:text="@string/lorem_ipsum"
            android:textSize="20sp" />
    </ScrollView>

</androidx.constraintlayout.widget.ConstraintLayout>

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

person Egis    schedule 11.02.2020

Установите фокус на самый верхний компонент пользовательского интерфейса, который вы хотите видеть

<ImageView
            android:focusable="true"
            android:layout_width="wrap_content"
            android:layout_height="wrap_content"
            android:layout_marginBottom="16dp"
            android:src="@drawable/ic_launcher" />
person Jitender Dev    schedule 23.10.2013

Попробуйте это может удовлетворить ваши требования.

   <?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:background="#cccfff"
    android:gravity="center"
    android:orientation="vertical" >

    <LinearLayout
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:layout_gravity="center"
        android:layout_margin="10dp"
        android:background="#ffffff"
        android:gravity="center_vertical"
        android:orientation="vertical"
        android:paddingBottom="40dp"
        android:paddingLeft="20dp"
        android:paddingRight="20dp"
        android:paddingTop="40dp" >

        <ImageView
            android:layout_width="wrap_content"
            android:layout_height="wrap_content"
            android:layout_marginBottom="16dp"
            android:src="@drawable/ic_launcher" />

        <TextView
            android:id="@+id/tip_title"
            android:layout_width="wrap_content"
            android:layout_height="wrap_content"
            android:layout_marginBottom="12dp"
            android:text="Title" />

        <TextView
            android:id="@+id/tip_description"
            android:layout_width="match_parent"
            android:layout_height="wrap_content"
            android:text="biruDescription description..." />
    </LinearLayout>

</LinearLayout>

Еще одна строка в вашем java-коде

TextView tip_description = (TextView) findViewById(R.id.tip_description);
        tip_description.setMovementMethod(new ScrollingMovementMethod());

Это прокрутит ваше описание, а не весь макет.

person Biraj Zalavadia    schedule 23.10.2013
comment
LinearLayout не центрируется по вертикали, если текст tip_description короткий. - person Egis; 23.10.2013
comment
Ну, это лучшее решение на данный момент, но я бы хотел, чтобы весь LinearLayout прокручивался, а не только TextView внутри него. Я гуглю уже час, и теперь у меня сложилось впечатление, что получить то, что я хочу, невозможно. Ну что ж... - person Egis; 23.10.2013

Просто используйте мой класс CenteringLinearLayout ниже.

import android.content.Context
import android.support.constraint.ConstraintLayout
import android.util.AttributeSet
import android.view.View
import android.widget.LinearLayout

class CenteringLinearLayout: LinearLayout {

    constructor(context: Context, attrs: AttributeSet, defStyle: Int) : super(context, attrs, defStyle)
    constructor(context: Context, attrs: AttributeSet) : super(context, attrs)
    constructor(context: Context) : super(context)

    override fun onSizeChanged(w: Int, h: Int, oldw: Int, oldh: Int) {
        val parentView = this.parent as View
        if (h > parentView.height) {
            parentView.post {
                val params = parentView.layoutParams as ConstraintLayout.LayoutParams
                params.height = ConstraintLayout.LayoutParams.MATCH_CONSTRAINT
                parentView.layoutParams = params
            }
        } else {
            val params = parentView.layoutParams
            params.height = ConstraintLayout.LayoutParams.WRAP_CONTENT
            parentView.layoutParams = params
        }
        super.onSizeChanged(w, h, oldw, oldh)
    }
}
person Salih    schedule 02.12.2018

Попробуйте установить поля и отступы в ScrollView

person Day    schedule 23.10.2013
comment
Это не помогает. Прежде всего, мой ScrollView не может иметь полей. Он должен занимать весь экран. Также у него не может быть отступов, потому что эти отступы также применяются к полосе прокрутки ScrollView справа, и полоса прокрутки должна иметь возможность прокручиваться сверху вниз экрана. - person Egis; 23.10.2013

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

<LinearLayout
    android:orientation="vertical"
    android:layout_width="fill_parent"
    android:layout_height="fill_parent"
    android:gravity="center">

    <ScrollView
        android:orientation="vertical"
        android:layout_width="match_parent"
        android:layout_height="wrap_content">

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

        <!-- Content here -->

        </LinearLayout>
    </ScrollView>
</LinearLayout>
person Borzh    schedule 01.05.2015