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

Остановить CollapsingToolbar от сбрасывания после того, как NestedScrollView закончил контент для прокрутки

В Android, как я могу заставить CollapsingToolbar прекратить свертывание, если у NestedScrollView заканчивается контент для прокрутки? Эта функциональность в настоящее время существует в приложении "Контакты" на Android 5.1.1. Однако в моем коде, когда NestedScrollView перестает прокручиваться, панель инструментов продолжает сбрасываться, оставляя пробел между ними.

<?xml version="1.0" encoding="utf-8"?>
<android.support.design.widget.CoordinatorLayout xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:app="http://schemas.android.com/apk/res-auto"
    xmlns:tools="http://schemas.android.com/tools"
    android:id="@+id/main_content"
    android:layout_width="match_parent"
    android:layout_height="match_parent">
    <android.support.design.widget.AppBarLayout
        android:id="@+id/appbar"
        android:layout_width="match_parent"
        android:layout_height="256dp"
        android:theme="@style/ThemeOverlay.AppCompat.Dark.ActionBar">
        <android.support.design.widget.CollapsingToolbarLayout
            android:id="@+id/collapsing_toolbar"
            android:layout_width="match_parent"
            android:layout_height="match_parent"
            app:layout_scrollFlags="scroll|exitUntilCollapsed"
            app:contentScrim="?attr/colorPrimary"
            app:expandedTitleMarginStart="@dimen/content_padding_normal"
            app:expandedTitleMarginEnd="64dp">
            <android.support.v7.widget.Toolbar
                android:id="@+id/toolbar"
                android:layout_width="match_parent"
                android:layout_height="?attr/actionBarSize"
                app:titleTextAppearance="@style/ActionBar.TitleText"
                app:layout_collapseMode="pin" />
        </android.support.design.widget.CollapsingToolbarLayout>
    </android.support.design.widget.AppBarLayout>
    <android.support.v4.widget.NestedScrollView
        android:layout_width="match_parent"
        android:layout_height="match_parent"
        app:layout_behavior="@string/appbar_scrolling_view_behavior"
        android:scrollbars="none">
        <LinearLayout
            android:layout_width="match_parent"
            android:layout_height="wrap_content"
            android:orientation="vertical"
            android:paddingBottom="@dimen/keyline_2">
            <android.support.v7.widget.CardView
                android:layout_width="match_parent"
                android:layout_height="wrap_content"
                android:layout_margin="@dimen/element_spacing_normal">
                <include
                    layout="@layout/ViewLoadingIndeterminate" />
                <LinearLayout
                    android:id="@+id/progress_status_container"
                    style="@style/ConnectionFieldContainer"
                    android:layout_width="match_parent"
                    android:layout_height="wrap_content"
                    android:layout_gravity="center_vertical"
                    android:orientation="vertical"
                    android:visibility="visible">
                    <Spinner
                        android:id="@+id/progress_status"
                        android:layout_width="match_parent"
                        style="@style/Text.ConnectionField" />
                    <TextView
                        style="@style/Text.ConnectionLabel"
                        android:text="@string/mobile.customer.connect.progress.status" />
                </LinearLayout>
            </android.support.v7.widget.CardView>
            <android.support.v7.widget.CardView
                android:layout_width="match_parent"
                android:layout_height="wrap_content"
                android:layout_margin="@dimen/element_spacing_normal">
                <LinearLayout
                    android:layout_width="match_parent"
                    android:layout_height="wrap_content"
                    android:orientation="vertical">
                    <LinearLayout
                        android:id="@+id/email1_container"
                        style="@style/ConnectionFieldContainer"
                        android:orientation="horizontal"
                        tools:visibility="visible">
                        <LinearLayout
                            android:layout_width="0dp"
                            android:layout_height="wrap_content"
                            android:layout_gravity="center_vertical"
                            android:layout_weight="1"
                            android:orientation="vertical">
                            <TextView
                                android:id="@+id/email1"
                                style="@style/Text.ConnectionField"
                                tools:text="[email protected]" />
                            <TextView
                                style="@style/Text.ConnectionLabel"
                                android:text="@string/mobile.customer.connect.email1" />
                        </LinearLayout>
                        <ImageButton
                            android:id="@+id/action_email1"
                            style="@style/Button.ConnectionAction"
                            android:src="@drawable/ic_email_black_24dp" />
                    </LinearLayout>
                    <LinearLayout
                        android:id="@+id/email2_container"
                        style="@style/ConnectionFieldContainer"
                        android:orientation="horizontal"
                        tools:visibility="visible">
                        <LinearLayout
                            android:layout_width="0dp"
                            android:layout_height="wrap_content"
                            android:layout_gravity="center_vertical"
                            android:layout_weight="1"
                            android:orientation="vertical">
                            <TextView
                                android:id="@+id/email2"
                                style="@style/Text.ConnectionField"
                                tools:text="[email protected]" />
                            <TextView
                                style="@style/Text.ConnectionLabel"
                                android:text="@string/mobile.customer.connect.email2" />
                        </LinearLayout>
                        <ImageButton
                            android:id="@+id/action_email2"
                            style="@style/Button.ConnectionAction"
                            android:src="@drawable/ic_email_black_24dp" />
                    </LinearLayout>
                    <LinearLayout
                        android:id="@+id/phone_day_container"
                        style="@style/ConnectionFieldContainer"
                        android:orientation="horizontal"
                        tools:visibility="visible">
                        <LinearLayout
                            android:layout_width="0dp"
                            android:layout_height="wrap_content"
                            android:layout_gravity="center_vertical"
                            android:layout_weight="1"
                            android:orientation="vertical">
                            <TextView
                                android:id="@+id/phone_day"
                                style="@style/Text.ConnectionField"
                                tools:text="801-555-1234" />
                            <TextView
                                style="@style/Text.ConnectionLabel"
                                android:text="@string/mobile.customer.connect.phone.day" />
                        </LinearLayout>
                        <ImageButton
                            android:id="@+id/action_call_phone_day"
                            style="@style/Button.ConnectionAction"
                            android:src="@drawable/ic_call_black_24dp" />
                        <ImageButton
                            android:id="@+id/action_text_phone_day"
                            style="@style/Button.ConnectionAction"
                            android:src="@drawable/ic_textsms_black_24dp" />
                    </LinearLayout>
        </LinearLayout>
    </android.support.v4.widget.NestedScrollView>
    <android.support.design.widget.FloatingActionButton
        android:id="@+id/create_reminder"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        app:layout_anchor="@id/collapsing_toolbar"
        app:layout_anchorGravity="bottom|right|end"
        app:borderWidth="0dp"
        app:elevation="@dimen/shadow_size"
        android:layout_marginBottom="@dimen/keyline_1"
        android:layout_marginRight="@dimen/keyline_1"
        android:src="@drawable/ic_alarm_add_white_24dp"
        app:backgroundTint="?attr/colorAccent" />
</android.support.design.widget.CoordinatorLayout>

example

4b9b3361

Ответ 1

Просто добавьте

android:layout_gravity="fill_vertical"

в вашем NestedScrollView.:)

Ответ 2

Сделайте NestedScrollView как

 <android.support.v4.widget.NestedScrollView
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    android:layout_gravity="fill_vertical"
    app:layout_behavior="@string/appbar_scrolling_view_behavior"
    android:scrollbars="none">

Сбой CollapsingToolbarLayout и содержимое NestedScrollView будет работать по мере необходимости.

Ответ 3

Сегодня я создал пользовательское поведение, которое делает именно это.

Он расширяет AppBarLayout.ScrollingViewBehavior, поэтому его необходимо установить в вашем представлении прокрутки (NestedScrollView или что-то еще).

Вы можете найти в Github, сообщите мне, если он работает.

Ключевая часть программно устанавливает свернутую высоту AppBarLayout на основе высоты содержимого, так что, когда она заканчивается, прокрутка останавливается.

Ответ 4

Быстрое решение, которое может оказаться неприемлемым, - в создании активности - измеряет высоту экрана и назначает вашему ребенку вложенногоScrollView как minimunHeight. Это не предотвратит прокрутку Appbar, но ваш контент будет прокручиваться полностью.

 //Calculate screen height in pixels
 DisplayMetrics displaymetrics = new DisplayMetrics();
 getWindowManager().getDefaultDisplay().getMetrics(displaymetrics);
 mScreenHeight = displaymetrics.heightPixels;

 //Get Statusbar size
 int statusBatHeight = 0;
 int resourceId = getResources().getIdentifier("status_bar_height", "dimen", "android");
 if (resourceId > 0) {
      mStatusBarHeight = getResources().getDimensionPixelSize(resourceId);
 }

 mContainer = (FrameLayout) findViewById(R.id.fragment_container);
 mContainer.setMinimumHeight(mScreenHeight - mStatusBarHeight);

Другим решением (а не быстрым) было бы расширение NestedScrollView и переопределение dispatchNestedPreScroll(). Этот метод используется для указания компоновки координатора, что у вас есть прокрутка определенного количества пикселей. Идея состоит в том, чтобы вычислить, если вы уже прокрутили все пиксели, а затем вызовите super.dispatchNestedScrollView() или нет.

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

Все становится немного сложнее с броском.

Ответ 5

Добавьте строку ниже

android:layout_gravity="fill_vertical"

к вашему вложенному ScrollView

Ответ 6

Я предлагаю использовать решение natario вместе с ниже фрагментом кода, чтобы избежать прокрутки appBarLayout при прокрутке.

app:scrimVisibleHeightTrigger="?attr/actionBarSize"