Stop CollapsingToolbar from collapsing after NestedScrollView runs out of content to scroll

我的未来我决定 提交于 2019-12-02 22:07:31

Just add

android:layout_gravity="fill_vertical"

in your NestedScrollView. :)

Today I made a custom Behavior that does just this.

It extends AppBarLayout.ScrollingViewBehavior, so must be set on your scrolling view (NestedScrollView or whatever).

You can find it on Github, let me know if it works.

The key part is programmatically setting the AppBarLayout collapsed height based on the content height, so that when it’s over, the scrolling stops.

Make your NestedScrollView as

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

The CollapsingToolbarLayout will collapse and NestedScrollView contents will work as you need.

a Quick solution that may not be suitable is, in activity creation, measure the screen height and assign to your nestedScrollView child as minimunHeight. This wont prevent the Appbar from scrolling, but your content will scroll all the way up.

 //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);

Another solution (not the quick one) would be to extend NestedScrollView and override dispatchNestedPreScroll(). This method it is used to tell Coordinator Layout that you have scroll certain amount of pixels. The idea is to calculate if you have already scrolled all the pixels and then call super.dispatchNestedScrollView() or not.

To calculate if you have already displayed all the content you will need the screen size, iterate through your children to measure the content, and how much have you already scrolled.

Things get a little more complicated with the fling.

Add below line

android:layout_gravity="fill_vertical"

to your Nested ScrollView

DPanic284

I suggest to use natario's solution along with below piece of code to avoid scrimming appBarLayout when scrolling.

app:scrimVisibleHeightTrigger="?attr/actionBarSize"

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!