Don't collapse Toolbar when RecyclerView fits the screen










31

















I've made an app using Android Design Library, with a Toolbar and TabLayout.
Actually 2 tabs are present, both with 2 RecyclerView, that automatically collapse the Toolbar when scrolled.



My question is: can I disable Toolbar collapsing when RecyclerView has few items and completely fits the screen (like in TAB 2)?



I've seen a lot of examples like CheeseSquare, made by a Google employee where the issue is still present: even if the RecyclerView has just 1 item, the toolbar keeps hiding on scroll.



enter image description here



I think I can just find out if the first item of the RecyclerView is visible on screen and if yes disable toolbar collapsing. The former is easy to implement, what about the latter?



This is my layout:



<android.support.design.widget.CoordinatorLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:app="http://schemas.android.com/apk/res-auto"
android:id="@+id/coordinator_layout"
android:layout_width="match_parent"
android:layout_height="match_parent">

<android.support.design.widget.AppBarLayout
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:fitsSystemWindows="true"
android:theme="@style/ThemeOverlay.AppCompat.Dark.ActionBar">

<android.support.v7.widget.Toolbar
android:id="@+id/toolbar"
android:layout_width="match_parent"
android:layout_height="wrap_content"
app:layout_scrollFlags="scroll|enterAlwaysCollapsed"
android:background="?attr/colorPrimary"
app:theme="@style/ThemeOverlay.AppCompat.Dark.ActionBar"
app:popupTheme="@style/ThemeOverlay.AppCompat.Light"/>

<android.support.design.widget.TabLayout
android:id="@+id/tab_layout"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:background="@color/glucosio_pink"
app:tabSelectedTextColor="@android:color/white"
app:tabIndicatorColor="@color/glucosio_accent"
app:tabTextColor="#80ffffff"/>
</android.support.design.widget.AppBarLayout>

<android.support.v4.view.ViewPager
android:id="@+id/pager"
app:layout_behavior="@string/appbar_scrolling_view_behavior"
android:layout_width="match_parent"
android:layout_height="wrap_content"/>

<android.support.design.widget.FloatingActionButton
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:id="@+id/main_fab"
android:layout_margin="16dp"
android:onClick="onFabClicked"
app:backgroundTint="@color/glucosio_accent"
android:src="@drawable/ic_add_black_24dp"
android:layout_gravity="bottom|right"
/>
</android.support.design.widget.CoordinatorLayout>














share|improve this question
























  • Can you tell me how you creating this gif?

    – Pratik Butani
    Sep 16 '15 at 4:40






  • 1





    Hi @PratikButani! I've found the gif on internet (mzgreen.github.io/2015/06/23/…). BTW, you can use services like gifs.com to create a gif from a YouTube video.

    – Paolo Rotolo
    Sep 16 '15 at 13:18











  • Twitted to that person with your link :) May he will help you. Thanks :) twitter.com/pratik13butani/status/644355243174526976

    – Pratik Butani
    Sep 17 '15 at 3:41












  • What do expect it to work? Let's say that you collapse the Toolbar on first page, then you swipe to second page. What should happen? Toolbar is hidden and you can't show it because there is too few items. And for disabling Toolbar scrolling - it may be possible, I will play with it later. Maybe a custom behavior will be solution.

    – Michał Z.
    Sep 17 '15 at 7:17






  • 1





    Please write your solution in a proper answer, so that it's easier to find.

    – PicPuc
    Sep 20 '15 at 12:34















31

















I've made an app using Android Design Library, with a Toolbar and TabLayout.
Actually 2 tabs are present, both with 2 RecyclerView, that automatically collapse the Toolbar when scrolled.



My question is: can I disable Toolbar collapsing when RecyclerView has few items and completely fits the screen (like in TAB 2)?



I've seen a lot of examples like CheeseSquare, made by a Google employee where the issue is still present: even if the RecyclerView has just 1 item, the toolbar keeps hiding on scroll.



enter image description here



I think I can just find out if the first item of the RecyclerView is visible on screen and if yes disable toolbar collapsing. The former is easy to implement, what about the latter?



This is my layout:



<android.support.design.widget.CoordinatorLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:app="http://schemas.android.com/apk/res-auto"
android:id="@+id/coordinator_layout"
android:layout_width="match_parent"
android:layout_height="match_parent">

<android.support.design.widget.AppBarLayout
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:fitsSystemWindows="true"
android:theme="@style/ThemeOverlay.AppCompat.Dark.ActionBar">

<android.support.v7.widget.Toolbar
android:id="@+id/toolbar"
android:layout_width="match_parent"
android:layout_height="wrap_content"
app:layout_scrollFlags="scroll|enterAlwaysCollapsed"
android:background="?attr/colorPrimary"
app:theme="@style/ThemeOverlay.AppCompat.Dark.ActionBar"
app:popupTheme="@style/ThemeOverlay.AppCompat.Light"/>

<android.support.design.widget.TabLayout
android:id="@+id/tab_layout"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:background="@color/glucosio_pink"
app:tabSelectedTextColor="@android:color/white"
app:tabIndicatorColor="@color/glucosio_accent"
app:tabTextColor="#80ffffff"/>
</android.support.design.widget.AppBarLayout>

<android.support.v4.view.ViewPager
android:id="@+id/pager"
app:layout_behavior="@string/appbar_scrolling_view_behavior"
android:layout_width="match_parent"
android:layout_height="wrap_content"/>

<android.support.design.widget.FloatingActionButton
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:id="@+id/main_fab"
android:layout_margin="16dp"
android:onClick="onFabClicked"
app:backgroundTint="@color/glucosio_accent"
android:src="@drawable/ic_add_black_24dp"
android:layout_gravity="bottom|right"
/>
</android.support.design.widget.CoordinatorLayout>














share|improve this question
























  • Can you tell me how you creating this gif?

    – Pratik Butani
    Sep 16 '15 at 4:40






  • 1





    Hi @PratikButani! I've found the gif on internet (mzgreen.github.io/2015/06/23/…). BTW, you can use services like gifs.com to create a gif from a YouTube video.

    – Paolo Rotolo
    Sep 16 '15 at 13:18











  • Twitted to that person with your link :) May he will help you. Thanks :) twitter.com/pratik13butani/status/644355243174526976

    – Pratik Butani
    Sep 17 '15 at 3:41












  • What do expect it to work? Let's say that you collapse the Toolbar on first page, then you swipe to second page. What should happen? Toolbar is hidden and you can't show it because there is too few items. And for disabling Toolbar scrolling - it may be possible, I will play with it later. Maybe a custom behavior will be solution.

    – Michał Z.
    Sep 17 '15 at 7:17






  • 1





    Please write your solution in a proper answer, so that it's easier to find.

    – PicPuc
    Sep 20 '15 at 12:34













31












31








31


19








I've made an app using Android Design Library, with a Toolbar and TabLayout.
Actually 2 tabs are present, both with 2 RecyclerView, that automatically collapse the Toolbar when scrolled.



My question is: can I disable Toolbar collapsing when RecyclerView has few items and completely fits the screen (like in TAB 2)?



I've seen a lot of examples like CheeseSquare, made by a Google employee where the issue is still present: even if the RecyclerView has just 1 item, the toolbar keeps hiding on scroll.



enter image description here



I think I can just find out if the first item of the RecyclerView is visible on screen and if yes disable toolbar collapsing. The former is easy to implement, what about the latter?



This is my layout:



<android.support.design.widget.CoordinatorLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:app="http://schemas.android.com/apk/res-auto"
android:id="@+id/coordinator_layout"
android:layout_width="match_parent"
android:layout_height="match_parent">

<android.support.design.widget.AppBarLayout
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:fitsSystemWindows="true"
android:theme="@style/ThemeOverlay.AppCompat.Dark.ActionBar">

<android.support.v7.widget.Toolbar
android:id="@+id/toolbar"
android:layout_width="match_parent"
android:layout_height="wrap_content"
app:layout_scrollFlags="scroll|enterAlwaysCollapsed"
android:background="?attr/colorPrimary"
app:theme="@style/ThemeOverlay.AppCompat.Dark.ActionBar"
app:popupTheme="@style/ThemeOverlay.AppCompat.Light"/>

<android.support.design.widget.TabLayout
android:id="@+id/tab_layout"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:background="@color/glucosio_pink"
app:tabSelectedTextColor="@android:color/white"
app:tabIndicatorColor="@color/glucosio_accent"
app:tabTextColor="#80ffffff"/>
</android.support.design.widget.AppBarLayout>

<android.support.v4.view.ViewPager
android:id="@+id/pager"
app:layout_behavior="@string/appbar_scrolling_view_behavior"
android:layout_width="match_parent"
android:layout_height="wrap_content"/>

<android.support.design.widget.FloatingActionButton
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:id="@+id/main_fab"
android:layout_margin="16dp"
android:onClick="onFabClicked"
app:backgroundTint="@color/glucosio_accent"
android:src="@drawable/ic_add_black_24dp"
android:layout_gravity="bottom|right"
/>
</android.support.design.widget.CoordinatorLayout>














share|improve this question


















I've made an app using Android Design Library, with a Toolbar and TabLayout.
Actually 2 tabs are present, both with 2 RecyclerView, that automatically collapse the Toolbar when scrolled.



My question is: can I disable Toolbar collapsing when RecyclerView has few items and completely fits the screen (like in TAB 2)?



I've seen a lot of examples like CheeseSquare, made by a Google employee where the issue is still present: even if the RecyclerView has just 1 item, the toolbar keeps hiding on scroll.



enter image description here



I think I can just find out if the first item of the RecyclerView is visible on screen and if yes disable toolbar collapsing. The former is easy to implement, what about the latter?



This is my layout:



<android.support.design.widget.CoordinatorLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:app="http://schemas.android.com/apk/res-auto"
android:id="@+id/coordinator_layout"
android:layout_width="match_parent"
android:layout_height="match_parent">

<android.support.design.widget.AppBarLayout
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:fitsSystemWindows="true"
android:theme="@style/ThemeOverlay.AppCompat.Dark.ActionBar">

<android.support.v7.widget.Toolbar
android:id="@+id/toolbar"
android:layout_width="match_parent"
android:layout_height="wrap_content"
app:layout_scrollFlags="scroll|enterAlwaysCollapsed"
android:background="?attr/colorPrimary"
app:theme="@style/ThemeOverlay.AppCompat.Dark.ActionBar"
app:popupTheme="@style/ThemeOverlay.AppCompat.Light"/>

<android.support.design.widget.TabLayout
android:id="@+id/tab_layout"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:background="@color/glucosio_pink"
app:tabSelectedTextColor="@android:color/white"
app:tabIndicatorColor="@color/glucosio_accent"
app:tabTextColor="#80ffffff"/>
</android.support.design.widget.AppBarLayout>

<android.support.v4.view.ViewPager
android:id="@+id/pager"
app:layout_behavior="@string/appbar_scrolling_view_behavior"
android:layout_width="match_parent"
android:layout_height="wrap_content"/>

<android.support.design.widget.FloatingActionButton
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:id="@+id/main_fab"
android:layout_margin="16dp"
android:onClick="onFabClicked"
app:backgroundTint="@color/glucosio_accent"
android:src="@drawable/ic_add_black_24dp"
android:layout_gravity="bottom|right"
/>
</android.support.design.widget.CoordinatorLayout>











android toolbar android-recyclerview appcompat android-design-library






share|improve this question















share|improve this question













share|improve this question




share|improve this question








edited Sep 21 '15 at 15:50







Paolo Rotolo

















asked Sep 4 '15 at 19:04









Paolo RotoloPaolo Rotolo

7301918




7301918












  • Can you tell me how you creating this gif?

    – Pratik Butani
    Sep 16 '15 at 4:40






  • 1





    Hi @PratikButani! I've found the gif on internet (mzgreen.github.io/2015/06/23/…). BTW, you can use services like gifs.com to create a gif from a YouTube video.

    – Paolo Rotolo
    Sep 16 '15 at 13:18











  • Twitted to that person with your link :) May he will help you. Thanks :) twitter.com/pratik13butani/status/644355243174526976

    – Pratik Butani
    Sep 17 '15 at 3:41












  • What do expect it to work? Let's say that you collapse the Toolbar on first page, then you swipe to second page. What should happen? Toolbar is hidden and you can't show it because there is too few items. And for disabling Toolbar scrolling - it may be possible, I will play with it later. Maybe a custom behavior will be solution.

    – Michał Z.
    Sep 17 '15 at 7:17






  • 1





    Please write your solution in a proper answer, so that it's easier to find.

    – PicPuc
    Sep 20 '15 at 12:34

















  • Can you tell me how you creating this gif?

    – Pratik Butani
    Sep 16 '15 at 4:40






  • 1





    Hi @PratikButani! I've found the gif on internet (mzgreen.github.io/2015/06/23/…). BTW, you can use services like gifs.com to create a gif from a YouTube video.

    – Paolo Rotolo
    Sep 16 '15 at 13:18











  • Twitted to that person with your link :) May he will help you. Thanks :) twitter.com/pratik13butani/status/644355243174526976

    – Pratik Butani
    Sep 17 '15 at 3:41












  • What do expect it to work? Let's say that you collapse the Toolbar on first page, then you swipe to second page. What should happen? Toolbar is hidden and you can't show it because there is too few items. And for disabling Toolbar scrolling - it may be possible, I will play with it later. Maybe a custom behavior will be solution.

    – Michał Z.
    Sep 17 '15 at 7:17






  • 1





    Please write your solution in a proper answer, so that it's easier to find.

    – PicPuc
    Sep 20 '15 at 12:34
















Can you tell me how you creating this gif?

– Pratik Butani
Sep 16 '15 at 4:40





Can you tell me how you creating this gif?

– Pratik Butani
Sep 16 '15 at 4:40




1




1





Hi @PratikButani! I've found the gif on internet (mzgreen.github.io/2015/06/23/…). BTW, you can use services like gifs.com to create a gif from a YouTube video.

– Paolo Rotolo
Sep 16 '15 at 13:18





Hi @PratikButani! I've found the gif on internet (mzgreen.github.io/2015/06/23/…). BTW, you can use services like gifs.com to create a gif from a YouTube video.

– Paolo Rotolo
Sep 16 '15 at 13:18













Twitted to that person with your link :) May he will help you. Thanks :) twitter.com/pratik13butani/status/644355243174526976

– Pratik Butani
Sep 17 '15 at 3:41






Twitted to that person with your link :) May he will help you. Thanks :) twitter.com/pratik13butani/status/644355243174526976

– Pratik Butani
Sep 17 '15 at 3:41














What do expect it to work? Let's say that you collapse the Toolbar on first page, then you swipe to second page. What should happen? Toolbar is hidden and you can't show it because there is too few items. And for disabling Toolbar scrolling - it may be possible, I will play with it later. Maybe a custom behavior will be solution.

– Michał Z.
Sep 17 '15 at 7:17





What do expect it to work? Let's say that you collapse the Toolbar on first page, then you swipe to second page. What should happen? Toolbar is hidden and you can't show it because there is too few items. And for disabling Toolbar scrolling - it may be possible, I will play with it later. Maybe a custom behavior will be solution.

– Michał Z.
Sep 17 '15 at 7:17




1




1





Please write your solution in a proper answer, so that it's easier to find.

– PicPuc
Sep 20 '15 at 12:34





Please write your solution in a proper answer, so that it's easier to find.

– PicPuc
Sep 20 '15 at 12:34












8 Answers
8






active

oldest

votes


















25














Final Solution (thanks Michał Z.)


Methods to turn off/on Toolbar scrolling:



public void turnOffToolbarScrolling() 
Toolbar mToolbar = (Toolbar) findViewById(R.id.toolbar);
AppBarLayout appBarLayout = (AppBarLayout) findViewById(R.id.appbar_layout);

//turn off scrolling
AppBarLayout.LayoutParams toolbarLayoutParams = (AppBarLayout.LayoutParams) mToolbar.getLayoutParams();
toolbarLayoutParams.setScrollFlags(0);
mToolbar.setLayoutParams(toolbarLayoutParams);

CoordinatorLayout.LayoutParams appBarLayoutParams = (CoordinatorLayout.LayoutParams) appBarLayout.getLayoutParams();
appBarLayoutParams.setBehavior(null);
appBarLayout.setLayoutParams(appBarLayoutParams);


public void turnOnToolbarScrolling() AppBarLayout.LayoutParams.SCROLL_FLAG_ENTER_ALWAYS);
mToolbar.setLayoutParams(toolbarLayoutParams);

CoordinatorLayout.LayoutParams appBarLayoutParams = (CoordinatorLayout.LayoutParams) appBarLayout.getLayoutParams();
appBarLayoutParams.setBehavior(new AppBarLayout.Behavior());
appBarLayout.setLayoutParams(appBarLayoutParams);





Find out if last item of RecyclerView is visible in my Fragment.

If yes, disable scrolling:



public void updateToolbarBehaviour()
if (mLayoutManager.findLastCompletelyVisibleItemPosition() == items.size()-1)
((MainActivity) getActivity()).turnOffToolbarScrolling();
else
((MainActivity)getActivity()).turnOnToolbarScrolling();







share|improve this answer


















  • 2





    You need to call updateToolbarBehaviour() with a delay (using Handler-Runnable) for the first time. Otherwise, the method findLastCompletelyVisibleItemPosition() returns "-1" initially.

    – Ugurcan Yildirim
    Jan 6 '17 at 12:11












  • Still this solution is working. And for collapsing tool bar also.

    – Pankaj Kumar
    Sep 4 '18 at 7:17











  • Hell lot of code for a simple logical stuff. It gets even more complicated while using fragment inside an activity with a toolbar.

    – Sai Kiran
    Sep 29 '18 at 8:23












  • Where do you put updateToolbarBehaviour()?

    – mFeinstein
    Oct 26 '18 at 17:41


















7














You can check if the last item in RecyclerView is visible. If it's not then turn off scrolling programmatically using this method:



 //turn off scrolling
AppBarLayout.LayoutParams toolbarLayoutParams = (AppBarLayout.LayoutParams) mToolbar.getLayoutParams();
toolbarLayoutParams.setScrollFlags(0);
mToolbar.setLayoutParams(toolbarLayoutParams);

CoordinatorLayout.LayoutParams appBarLayoutParams = (CoordinatorLayout.LayoutParams) appBarLayout.getLayoutParams();
appBarLayoutParams.setBehavior(null);
appBarLayout.setLayoutParams(appBarLayoutParams);





share|improve this answer























  • Works well, thanks! I've updated my question with both off and on methods.

    – Paolo Rotolo
    Sep 19 '15 at 19:55











  • Works well, but if the content of the view that has app:layout_behavior="@string/appbar_scrolling_view_behavior", and also has layout_height="match_parent" the content won't center after turning off the scrolling

    – Earwin delos Santos
    Oct 1 '15 at 4:36











  • this works well just to disable the scroll, but if to re-enable the same for different fragment wont work, on setting the scroll Flags progrmatically.

    – pallavi
    Sep 20 '16 at 7:15


















7














RecyclerView now (since version 23.2) supports wrap_content. Just use wrap_content as the height.






share|improve this answer




















  • 2





    Unfortunately it does not work for me when I wrap RecyclerView with SwipeRefreshLayout

    – Artem_Iens
    Apr 28 '17 at 16:16











  • This worked for me using a NestedScrollView. Thanks!

    – rjr-apps
    Sep 15 '17 at 19:46











  • didn't work for me

    – mFeinstein
    Oct 26 '18 at 17:24


















3














I took a slightly different approach to solve this.



I created a custom AppBarBehavior that disables its self based on cells.



public class CustomAppBarBehavior extends AppBarLayout.Behavior 

private RecyclerView recyclerView;
private boolean enabled;

public CustomAppBarBehavior()


public CustomAppBarBehavior(Context context, AttributeSet attrs)
super(context, attrs);


@Override
public boolean onInterceptTouchEvent(CoordinatorLayout parent, AppBarLayout child, MotionEvent ev)
updatedEnabled();
return enabled && super.onInterceptTouchEvent(parent, child, ev);


@Override
public boolean onStartNestedScroll(CoordinatorLayout parent, AppBarLayout child, View directTargetChild, View target, int nestedScrollAxes)
return enabled && super.onStartNestedScroll(parent, child, directTargetChild, target, nestedScrollAxes);


@Override
public boolean onNestedFling(CoordinatorLayout coordinatorLayout, AppBarLayout child, View target, float velocityX, float velocityY, boolean consumed)
return enabled && super.onNestedFling(coordinatorLayout, child, target, velocityX, velocityY, consumed);


private void updatedEnabled()
enabled = false;
if(recyclerView != null)
RecyclerView.Adapter adapter = recyclerView.getAdapter();
if (adapter != null)
int count = adapter.getItemCount();
RecyclerView.LayoutManager layoutManager = recyclerView.getLayoutManager();
if (layoutManager != null)
int lastItem = 0;
if (layoutManager instanceof LinearLayoutManager)
LinearLayoutManager linearLayoutManager = (LinearLayoutManager) layoutManager;
lastItem = Math.abs(linearLayoutManager.findLastCompletelyVisibleItemPosition());
else if (layoutManager instanceof StaggeredGridLayoutManager)
StaggeredGridLayoutManager staggeredGridLayoutManager = (StaggeredGridLayoutManager) layoutManager;
int lastItems = staggeredGridLayoutManager.findLastCompletelyVisibleItemPositions(new int[staggeredGridLayoutManager.getSpanCount()]);
lastItem = Math.abs(lastItems[lastItems.length - 1]);

enabled = lastItem < count - 1;





public void setRecyclerView(RecyclerView recyclerView)
this.recyclerView = recyclerView;




Then set the custom behavior on the app bar layout



appBarBehavior = new CustomAppBarBehavior();
CoordinatorLayout.LayoutParams appBarLayoutParams = (CoordinatorLayout.LayoutParams) appBarLayout.getLayoutParams();
appBarLayoutParams.setBehavior(appBarBehavior);
appBarLayout.setLayoutParams(appBarLayoutParams);


Last on page change of the view pager updated the RecyclerView on the behavior



private ViewPager.OnPageChangeListener pageChangeListener = new ViewPager.OnPageChangeListener() 
@Override
public void onPageScrolled(int position, float positionOffset, int positionOffsetPixels)

@Override
public void onPageSelected(final int position)
appBarLayout.setExpanded(true, true);
appBarLayout.post(new Runnable()
@Override
public void run()
appBarBehavior.setRecyclerView(childFragments.get(position).getRecyclerView());

);


@Override
public void onPageScrollStateChanged(int state)
;


This should work with changing datasets.






share|improve this answer

























  • Really interesting. Thanks for sharing.

    – Paolo Rotolo
    Oct 3 '15 at 13:39











  • Oh also you need to reset the recyclerview on rotation keeping in mind that the view pager give index 0 after being restored even if its not really on that page. Fragments are a joy.

    – Stuart Campbell
    Oct 3 '15 at 14:02


















1














Add this code after you change data in your adapter:



recyclerView.afterMeasured 
val isTurnedOff = recyclerView.turnOffNestedScrollingIfEnoughItems()
if (isTurnedOff) appBarLayout.setExpanded(true)



And this is the functions:



inline fun <T: View> T.afterMeasured(crossinline action: T.() -> Unit) 
viewTreeObserver.addOnGlobalLayoutListener(object : ViewTreeObserver.OnGlobalLayoutListener
override fun onGlobalLayout()
viewTreeObserver.removeOnGlobalLayoutListener(this)
action()

)



fun RecyclerView.turnOffNestedScrollingIfEnoughItems(): Boolean
val lm = (layoutManager as LinearLayoutManager)
val count = if (lm.itemCount <= 0) 0 else lm.itemCount - 1
val isFirstVisible = lm.findFirstCompletelyVisibleItemPosition() == 0
val isLastItemVisible = lm.findLastCompletelyVisibleItemPosition() == count

isNestedScrollingEnabled = !(isLastItemVisible && isFirstVisible)
return isNestedScrollingEnabled.not()






share|improve this answer
































    -1














    You can add within your XML, the property layout_behaviour with value @string/appbar_scrolling_view_behavior this way:



    app:layout_behavior="@string/appbar_scrolling_view_behavior"





    share|improve this answer
































      -2














      //turn off scrolling
      AppBarLayout.LayoutParams toolbarLayoutParams = (AppBarLayout.LayoutParams) mToolbar.getLayoutParams();
      toolbarLayoutParams.setScrollFlags(0);
      mToolbar.setLayoutParams(toolbarLayoutParams);





      share|improve this answer
































        -2














        Just remove scroll from



        app:layout_scrollFlags="scroll|enterAlways"


        So it should be



        app:layout_scrollFlags="enterAlways"





        share|improve this answer


















        • 4





          This totally locks the CollapsingToolbarLayout from scrolling...

          – Rafal Zawadzki
          Jun 9 '17 at 14:51










        Your Answer






        StackExchange.ifUsing("editor", function ()
        StackExchange.using("externalEditor", function ()
        StackExchange.using("snippets", function ()
        StackExchange.snippets.init();
        );
        );
        , "code-snippets");

        StackExchange.ready(function()
        var channelOptions =
        tags: "".split(" "),
        id: "1"
        ;
        initTagRenderer("".split(" "), "".split(" "), channelOptions);

        StackExchange.using("externalEditor", function()
        // Have to fire editor after snippets, if snippets enabled
        if (StackExchange.settings.snippets.snippetsEnabled)
        StackExchange.using("snippets", function()
        createEditor();
        );

        else
        createEditor();

        );

        function createEditor()
        StackExchange.prepareEditor(
        heartbeatType: 'answer',
        autoActivateHeartbeat: false,
        convertImagesToLinks: true,
        noModals: true,
        showLowRepImageUploadWarning: true,
        reputationToPostImages: 10,
        bindNavPrevention: true,
        postfix: "",
        imageUploader:
        brandingHtml: "Powered by u003ca class="icon-imgur-white" href="https://imgur.com/"u003eu003c/au003e",
        contentPolicyHtml: "User contributions licensed under u003ca href="https://creativecommons.org/licenses/by-sa/3.0/"u003ecc by-sa 3.0 with attribution requiredu003c/au003e u003ca href="https://stackoverflow.com/legal/content-policy"u003e(content policy)u003c/au003e",
        allowUrls: true
        ,
        onDemand: true,
        discardSelector: ".discard-answer"
        ,immediatelyShowMarkdownHelp:true
        );



        );













        draft saved

        draft discarded


















        StackExchange.ready(
        function ()
        StackExchange.openid.initPostLogin('.new-post-login', 'https%3a%2f%2fstackoverflow.com%2fquestions%2f32404979%2fdont-collapse-toolbar-when-recyclerview-fits-the-screen%23new-answer', 'question_page');

        );

        Post as a guest















        Required, but never shown

























        8 Answers
        8






        active

        oldest

        votes








        8 Answers
        8






        active

        oldest

        votes









        active

        oldest

        votes






        active

        oldest

        votes









        25














        Final Solution (thanks Michał Z.)


        Methods to turn off/on Toolbar scrolling:



        public void turnOffToolbarScrolling() 
        Toolbar mToolbar = (Toolbar) findViewById(R.id.toolbar);
        AppBarLayout appBarLayout = (AppBarLayout) findViewById(R.id.appbar_layout);

        //turn off scrolling
        AppBarLayout.LayoutParams toolbarLayoutParams = (AppBarLayout.LayoutParams) mToolbar.getLayoutParams();
        toolbarLayoutParams.setScrollFlags(0);
        mToolbar.setLayoutParams(toolbarLayoutParams);

        CoordinatorLayout.LayoutParams appBarLayoutParams = (CoordinatorLayout.LayoutParams) appBarLayout.getLayoutParams();
        appBarLayoutParams.setBehavior(null);
        appBarLayout.setLayoutParams(appBarLayoutParams);


        public void turnOnToolbarScrolling() AppBarLayout.LayoutParams.SCROLL_FLAG_ENTER_ALWAYS);
        mToolbar.setLayoutParams(toolbarLayoutParams);

        CoordinatorLayout.LayoutParams appBarLayoutParams = (CoordinatorLayout.LayoutParams) appBarLayout.getLayoutParams();
        appBarLayoutParams.setBehavior(new AppBarLayout.Behavior());
        appBarLayout.setLayoutParams(appBarLayoutParams);





        Find out if last item of RecyclerView is visible in my Fragment.

        If yes, disable scrolling:



        public void updateToolbarBehaviour()
        if (mLayoutManager.findLastCompletelyVisibleItemPosition() == items.size()-1)
        ((MainActivity) getActivity()).turnOffToolbarScrolling();
        else
        ((MainActivity)getActivity()).turnOnToolbarScrolling();







        share|improve this answer


















        • 2





          You need to call updateToolbarBehaviour() with a delay (using Handler-Runnable) for the first time. Otherwise, the method findLastCompletelyVisibleItemPosition() returns "-1" initially.

          – Ugurcan Yildirim
          Jan 6 '17 at 12:11












        • Still this solution is working. And for collapsing tool bar also.

          – Pankaj Kumar
          Sep 4 '18 at 7:17











        • Hell lot of code for a simple logical stuff. It gets even more complicated while using fragment inside an activity with a toolbar.

          – Sai Kiran
          Sep 29 '18 at 8:23












        • Where do you put updateToolbarBehaviour()?

          – mFeinstein
          Oct 26 '18 at 17:41















        25














        Final Solution (thanks Michał Z.)


        Methods to turn off/on Toolbar scrolling:



        public void turnOffToolbarScrolling() 
        Toolbar mToolbar = (Toolbar) findViewById(R.id.toolbar);
        AppBarLayout appBarLayout = (AppBarLayout) findViewById(R.id.appbar_layout);

        //turn off scrolling
        AppBarLayout.LayoutParams toolbarLayoutParams = (AppBarLayout.LayoutParams) mToolbar.getLayoutParams();
        toolbarLayoutParams.setScrollFlags(0);
        mToolbar.setLayoutParams(toolbarLayoutParams);

        CoordinatorLayout.LayoutParams appBarLayoutParams = (CoordinatorLayout.LayoutParams) appBarLayout.getLayoutParams();
        appBarLayoutParams.setBehavior(null);
        appBarLayout.setLayoutParams(appBarLayoutParams);


        public void turnOnToolbarScrolling() AppBarLayout.LayoutParams.SCROLL_FLAG_ENTER_ALWAYS);
        mToolbar.setLayoutParams(toolbarLayoutParams);

        CoordinatorLayout.LayoutParams appBarLayoutParams = (CoordinatorLayout.LayoutParams) appBarLayout.getLayoutParams();
        appBarLayoutParams.setBehavior(new AppBarLayout.Behavior());
        appBarLayout.setLayoutParams(appBarLayoutParams);





        Find out if last item of RecyclerView is visible in my Fragment.

        If yes, disable scrolling:



        public void updateToolbarBehaviour()
        if (mLayoutManager.findLastCompletelyVisibleItemPosition() == items.size()-1)
        ((MainActivity) getActivity()).turnOffToolbarScrolling();
        else
        ((MainActivity)getActivity()).turnOnToolbarScrolling();







        share|improve this answer


















        • 2





          You need to call updateToolbarBehaviour() with a delay (using Handler-Runnable) for the first time. Otherwise, the method findLastCompletelyVisibleItemPosition() returns "-1" initially.

          – Ugurcan Yildirim
          Jan 6 '17 at 12:11












        • Still this solution is working. And for collapsing tool bar also.

          – Pankaj Kumar
          Sep 4 '18 at 7:17











        • Hell lot of code for a simple logical stuff. It gets even more complicated while using fragment inside an activity with a toolbar.

          – Sai Kiran
          Sep 29 '18 at 8:23












        • Where do you put updateToolbarBehaviour()?

          – mFeinstein
          Oct 26 '18 at 17:41













        25












        25








        25







        Final Solution (thanks Michał Z.)


        Methods to turn off/on Toolbar scrolling:



        public void turnOffToolbarScrolling() 
        Toolbar mToolbar = (Toolbar) findViewById(R.id.toolbar);
        AppBarLayout appBarLayout = (AppBarLayout) findViewById(R.id.appbar_layout);

        //turn off scrolling
        AppBarLayout.LayoutParams toolbarLayoutParams = (AppBarLayout.LayoutParams) mToolbar.getLayoutParams();
        toolbarLayoutParams.setScrollFlags(0);
        mToolbar.setLayoutParams(toolbarLayoutParams);

        CoordinatorLayout.LayoutParams appBarLayoutParams = (CoordinatorLayout.LayoutParams) appBarLayout.getLayoutParams();
        appBarLayoutParams.setBehavior(null);
        appBarLayout.setLayoutParams(appBarLayoutParams);


        public void turnOnToolbarScrolling() AppBarLayout.LayoutParams.SCROLL_FLAG_ENTER_ALWAYS);
        mToolbar.setLayoutParams(toolbarLayoutParams);

        CoordinatorLayout.LayoutParams appBarLayoutParams = (CoordinatorLayout.LayoutParams) appBarLayout.getLayoutParams();
        appBarLayoutParams.setBehavior(new AppBarLayout.Behavior());
        appBarLayout.setLayoutParams(appBarLayoutParams);





        Find out if last item of RecyclerView is visible in my Fragment.

        If yes, disable scrolling:



        public void updateToolbarBehaviour()
        if (mLayoutManager.findLastCompletelyVisibleItemPosition() == items.size()-1)
        ((MainActivity) getActivity()).turnOffToolbarScrolling();
        else
        ((MainActivity)getActivity()).turnOnToolbarScrolling();







        share|improve this answer













        Final Solution (thanks Michał Z.)


        Methods to turn off/on Toolbar scrolling:



        public void turnOffToolbarScrolling() 
        Toolbar mToolbar = (Toolbar) findViewById(R.id.toolbar);
        AppBarLayout appBarLayout = (AppBarLayout) findViewById(R.id.appbar_layout);

        //turn off scrolling
        AppBarLayout.LayoutParams toolbarLayoutParams = (AppBarLayout.LayoutParams) mToolbar.getLayoutParams();
        toolbarLayoutParams.setScrollFlags(0);
        mToolbar.setLayoutParams(toolbarLayoutParams);

        CoordinatorLayout.LayoutParams appBarLayoutParams = (CoordinatorLayout.LayoutParams) appBarLayout.getLayoutParams();
        appBarLayoutParams.setBehavior(null);
        appBarLayout.setLayoutParams(appBarLayoutParams);


        public void turnOnToolbarScrolling() AppBarLayout.LayoutParams.SCROLL_FLAG_ENTER_ALWAYS);
        mToolbar.setLayoutParams(toolbarLayoutParams);

        CoordinatorLayout.LayoutParams appBarLayoutParams = (CoordinatorLayout.LayoutParams) appBarLayout.getLayoutParams();
        appBarLayoutParams.setBehavior(new AppBarLayout.Behavior());
        appBarLayout.setLayoutParams(appBarLayoutParams);





        Find out if last item of RecyclerView is visible in my Fragment.

        If yes, disable scrolling:



        public void updateToolbarBehaviour()
        if (mLayoutManager.findLastCompletelyVisibleItemPosition() == items.size()-1)
        ((MainActivity) getActivity()).turnOffToolbarScrolling();
        else
        ((MainActivity)getActivity()).turnOnToolbarScrolling();








        share|improve this answer












        share|improve this answer



        share|improve this answer










        answered Sep 21 '15 at 15:53









        Paolo RotoloPaolo Rotolo

        7301918




        7301918







        • 2





          You need to call updateToolbarBehaviour() with a delay (using Handler-Runnable) for the first time. Otherwise, the method findLastCompletelyVisibleItemPosition() returns "-1" initially.

          – Ugurcan Yildirim
          Jan 6 '17 at 12:11












        • Still this solution is working. And for collapsing tool bar also.

          – Pankaj Kumar
          Sep 4 '18 at 7:17











        • Hell lot of code for a simple logical stuff. It gets even more complicated while using fragment inside an activity with a toolbar.

          – Sai Kiran
          Sep 29 '18 at 8:23












        • Where do you put updateToolbarBehaviour()?

          – mFeinstein
          Oct 26 '18 at 17:41












        • 2





          You need to call updateToolbarBehaviour() with a delay (using Handler-Runnable) for the first time. Otherwise, the method findLastCompletelyVisibleItemPosition() returns "-1" initially.

          – Ugurcan Yildirim
          Jan 6 '17 at 12:11












        • Still this solution is working. And for collapsing tool bar also.

          – Pankaj Kumar
          Sep 4 '18 at 7:17











        • Hell lot of code for a simple logical stuff. It gets even more complicated while using fragment inside an activity with a toolbar.

          – Sai Kiran
          Sep 29 '18 at 8:23












        • Where do you put updateToolbarBehaviour()?

          – mFeinstein
          Oct 26 '18 at 17:41







        2




        2





        You need to call updateToolbarBehaviour() with a delay (using Handler-Runnable) for the first time. Otherwise, the method findLastCompletelyVisibleItemPosition() returns "-1" initially.

        – Ugurcan Yildirim
        Jan 6 '17 at 12:11






        You need to call updateToolbarBehaviour() with a delay (using Handler-Runnable) for the first time. Otherwise, the method findLastCompletelyVisibleItemPosition() returns "-1" initially.

        – Ugurcan Yildirim
        Jan 6 '17 at 12:11














        Still this solution is working. And for collapsing tool bar also.

        – Pankaj Kumar
        Sep 4 '18 at 7:17





        Still this solution is working. And for collapsing tool bar also.

        – Pankaj Kumar
        Sep 4 '18 at 7:17













        Hell lot of code for a simple logical stuff. It gets even more complicated while using fragment inside an activity with a toolbar.

        – Sai Kiran
        Sep 29 '18 at 8:23






        Hell lot of code for a simple logical stuff. It gets even more complicated while using fragment inside an activity with a toolbar.

        – Sai Kiran
        Sep 29 '18 at 8:23














        Where do you put updateToolbarBehaviour()?

        – mFeinstein
        Oct 26 '18 at 17:41





        Where do you put updateToolbarBehaviour()?

        – mFeinstein
        Oct 26 '18 at 17:41













        7














        You can check if the last item in RecyclerView is visible. If it's not then turn off scrolling programmatically using this method:



         //turn off scrolling
        AppBarLayout.LayoutParams toolbarLayoutParams = (AppBarLayout.LayoutParams) mToolbar.getLayoutParams();
        toolbarLayoutParams.setScrollFlags(0);
        mToolbar.setLayoutParams(toolbarLayoutParams);

        CoordinatorLayout.LayoutParams appBarLayoutParams = (CoordinatorLayout.LayoutParams) appBarLayout.getLayoutParams();
        appBarLayoutParams.setBehavior(null);
        appBarLayout.setLayoutParams(appBarLayoutParams);





        share|improve this answer























        • Works well, thanks! I've updated my question with both off and on methods.

          – Paolo Rotolo
          Sep 19 '15 at 19:55











        • Works well, but if the content of the view that has app:layout_behavior="@string/appbar_scrolling_view_behavior", and also has layout_height="match_parent" the content won't center after turning off the scrolling

          – Earwin delos Santos
          Oct 1 '15 at 4:36











        • this works well just to disable the scroll, but if to re-enable the same for different fragment wont work, on setting the scroll Flags progrmatically.

          – pallavi
          Sep 20 '16 at 7:15















        7














        You can check if the last item in RecyclerView is visible. If it's not then turn off scrolling programmatically using this method:



         //turn off scrolling
        AppBarLayout.LayoutParams toolbarLayoutParams = (AppBarLayout.LayoutParams) mToolbar.getLayoutParams();
        toolbarLayoutParams.setScrollFlags(0);
        mToolbar.setLayoutParams(toolbarLayoutParams);

        CoordinatorLayout.LayoutParams appBarLayoutParams = (CoordinatorLayout.LayoutParams) appBarLayout.getLayoutParams();
        appBarLayoutParams.setBehavior(null);
        appBarLayout.setLayoutParams(appBarLayoutParams);





        share|improve this answer























        • Works well, thanks! I've updated my question with both off and on methods.

          – Paolo Rotolo
          Sep 19 '15 at 19:55











        • Works well, but if the content of the view that has app:layout_behavior="@string/appbar_scrolling_view_behavior", and also has layout_height="match_parent" the content won't center after turning off the scrolling

          – Earwin delos Santos
          Oct 1 '15 at 4:36











        • this works well just to disable the scroll, but if to re-enable the same for different fragment wont work, on setting the scroll Flags progrmatically.

          – pallavi
          Sep 20 '16 at 7:15













        7












        7








        7







        You can check if the last item in RecyclerView is visible. If it's not then turn off scrolling programmatically using this method:



         //turn off scrolling
        AppBarLayout.LayoutParams toolbarLayoutParams = (AppBarLayout.LayoutParams) mToolbar.getLayoutParams();
        toolbarLayoutParams.setScrollFlags(0);
        mToolbar.setLayoutParams(toolbarLayoutParams);

        CoordinatorLayout.LayoutParams appBarLayoutParams = (CoordinatorLayout.LayoutParams) appBarLayout.getLayoutParams();
        appBarLayoutParams.setBehavior(null);
        appBarLayout.setLayoutParams(appBarLayoutParams);





        share|improve this answer













        You can check if the last item in RecyclerView is visible. If it's not then turn off scrolling programmatically using this method:



         //turn off scrolling
        AppBarLayout.LayoutParams toolbarLayoutParams = (AppBarLayout.LayoutParams) mToolbar.getLayoutParams();
        toolbarLayoutParams.setScrollFlags(0);
        mToolbar.setLayoutParams(toolbarLayoutParams);

        CoordinatorLayout.LayoutParams appBarLayoutParams = (CoordinatorLayout.LayoutParams) appBarLayout.getLayoutParams();
        appBarLayoutParams.setBehavior(null);
        appBarLayout.setLayoutParams(appBarLayoutParams);






        share|improve this answer












        share|improve this answer



        share|improve this answer










        answered Sep 19 '15 at 17:30









        Michał Z.Michał Z.

        3,77111732




        3,77111732












        • Works well, thanks! I've updated my question with both off and on methods.

          – Paolo Rotolo
          Sep 19 '15 at 19:55











        • Works well, but if the content of the view that has app:layout_behavior="@string/appbar_scrolling_view_behavior", and also has layout_height="match_parent" the content won't center after turning off the scrolling

          – Earwin delos Santos
          Oct 1 '15 at 4:36











        • this works well just to disable the scroll, but if to re-enable the same for different fragment wont work, on setting the scroll Flags progrmatically.

          – pallavi
          Sep 20 '16 at 7:15

















        • Works well, thanks! I've updated my question with both off and on methods.

          – Paolo Rotolo
          Sep 19 '15 at 19:55











        • Works well, but if the content of the view that has app:layout_behavior="@string/appbar_scrolling_view_behavior", and also has layout_height="match_parent" the content won't center after turning off the scrolling

          – Earwin delos Santos
          Oct 1 '15 at 4:36











        • this works well just to disable the scroll, but if to re-enable the same for different fragment wont work, on setting the scroll Flags progrmatically.

          – pallavi
          Sep 20 '16 at 7:15
















        Works well, thanks! I've updated my question with both off and on methods.

        – Paolo Rotolo
        Sep 19 '15 at 19:55





        Works well, thanks! I've updated my question with both off and on methods.

        – Paolo Rotolo
        Sep 19 '15 at 19:55













        Works well, but if the content of the view that has app:layout_behavior="@string/appbar_scrolling_view_behavior", and also has layout_height="match_parent" the content won't center after turning off the scrolling

        – Earwin delos Santos
        Oct 1 '15 at 4:36





        Works well, but if the content of the view that has app:layout_behavior="@string/appbar_scrolling_view_behavior", and also has layout_height="match_parent" the content won't center after turning off the scrolling

        – Earwin delos Santos
        Oct 1 '15 at 4:36













        this works well just to disable the scroll, but if to re-enable the same for different fragment wont work, on setting the scroll Flags progrmatically.

        – pallavi
        Sep 20 '16 at 7:15





        this works well just to disable the scroll, but if to re-enable the same for different fragment wont work, on setting the scroll Flags progrmatically.

        – pallavi
        Sep 20 '16 at 7:15











        7














        RecyclerView now (since version 23.2) supports wrap_content. Just use wrap_content as the height.






        share|improve this answer




















        • 2





          Unfortunately it does not work for me when I wrap RecyclerView with SwipeRefreshLayout

          – Artem_Iens
          Apr 28 '17 at 16:16











        • This worked for me using a NestedScrollView. Thanks!

          – rjr-apps
          Sep 15 '17 at 19:46











        • didn't work for me

          – mFeinstein
          Oct 26 '18 at 17:24















        7














        RecyclerView now (since version 23.2) supports wrap_content. Just use wrap_content as the height.






        share|improve this answer




















        • 2





          Unfortunately it does not work for me when I wrap RecyclerView with SwipeRefreshLayout

          – Artem_Iens
          Apr 28 '17 at 16:16











        • This worked for me using a NestedScrollView. Thanks!

          – rjr-apps
          Sep 15 '17 at 19:46











        • didn't work for me

          – mFeinstein
          Oct 26 '18 at 17:24













        7












        7








        7







        RecyclerView now (since version 23.2) supports wrap_content. Just use wrap_content as the height.






        share|improve this answer















        RecyclerView now (since version 23.2) supports wrap_content. Just use wrap_content as the height.







        share|improve this answer














        share|improve this answer



        share|improve this answer








        edited Jun 13 '16 at 20:26

























        answered Mar 28 '16 at 4:19









        Eric CochranEric Cochran

        4,51353262




        4,51353262







        • 2





          Unfortunately it does not work for me when I wrap RecyclerView with SwipeRefreshLayout

          – Artem_Iens
          Apr 28 '17 at 16:16











        • This worked for me using a NestedScrollView. Thanks!

          – rjr-apps
          Sep 15 '17 at 19:46











        • didn't work for me

          – mFeinstein
          Oct 26 '18 at 17:24












        • 2





          Unfortunately it does not work for me when I wrap RecyclerView with SwipeRefreshLayout

          – Artem_Iens
          Apr 28 '17 at 16:16











        • This worked for me using a NestedScrollView. Thanks!

          – rjr-apps
          Sep 15 '17 at 19:46











        • didn't work for me

          – mFeinstein
          Oct 26 '18 at 17:24







        2




        2





        Unfortunately it does not work for me when I wrap RecyclerView with SwipeRefreshLayout

        – Artem_Iens
        Apr 28 '17 at 16:16





        Unfortunately it does not work for me when I wrap RecyclerView with SwipeRefreshLayout

        – Artem_Iens
        Apr 28 '17 at 16:16













        This worked for me using a NestedScrollView. Thanks!

        – rjr-apps
        Sep 15 '17 at 19:46





        This worked for me using a NestedScrollView. Thanks!

        – rjr-apps
        Sep 15 '17 at 19:46













        didn't work for me

        – mFeinstein
        Oct 26 '18 at 17:24





        didn't work for me

        – mFeinstein
        Oct 26 '18 at 17:24











        3














        I took a slightly different approach to solve this.



        I created a custom AppBarBehavior that disables its self based on cells.



        public class CustomAppBarBehavior extends AppBarLayout.Behavior 

        private RecyclerView recyclerView;
        private boolean enabled;

        public CustomAppBarBehavior()


        public CustomAppBarBehavior(Context context, AttributeSet attrs)
        super(context, attrs);


        @Override
        public boolean onInterceptTouchEvent(CoordinatorLayout parent, AppBarLayout child, MotionEvent ev)
        updatedEnabled();
        return enabled && super.onInterceptTouchEvent(parent, child, ev);


        @Override
        public boolean onStartNestedScroll(CoordinatorLayout parent, AppBarLayout child, View directTargetChild, View target, int nestedScrollAxes)
        return enabled && super.onStartNestedScroll(parent, child, directTargetChild, target, nestedScrollAxes);


        @Override
        public boolean onNestedFling(CoordinatorLayout coordinatorLayout, AppBarLayout child, View target, float velocityX, float velocityY, boolean consumed)
        return enabled && super.onNestedFling(coordinatorLayout, child, target, velocityX, velocityY, consumed);


        private void updatedEnabled()
        enabled = false;
        if(recyclerView != null)
        RecyclerView.Adapter adapter = recyclerView.getAdapter();
        if (adapter != null)
        int count = adapter.getItemCount();
        RecyclerView.LayoutManager layoutManager = recyclerView.getLayoutManager();
        if (layoutManager != null)
        int lastItem = 0;
        if (layoutManager instanceof LinearLayoutManager)
        LinearLayoutManager linearLayoutManager = (LinearLayoutManager) layoutManager;
        lastItem = Math.abs(linearLayoutManager.findLastCompletelyVisibleItemPosition());
        else if (layoutManager instanceof StaggeredGridLayoutManager)
        StaggeredGridLayoutManager staggeredGridLayoutManager = (StaggeredGridLayoutManager) layoutManager;
        int lastItems = staggeredGridLayoutManager.findLastCompletelyVisibleItemPositions(new int[staggeredGridLayoutManager.getSpanCount()]);
        lastItem = Math.abs(lastItems[lastItems.length - 1]);

        enabled = lastItem < count - 1;





        public void setRecyclerView(RecyclerView recyclerView)
        this.recyclerView = recyclerView;




        Then set the custom behavior on the app bar layout



        appBarBehavior = new CustomAppBarBehavior();
        CoordinatorLayout.LayoutParams appBarLayoutParams = (CoordinatorLayout.LayoutParams) appBarLayout.getLayoutParams();
        appBarLayoutParams.setBehavior(appBarBehavior);
        appBarLayout.setLayoutParams(appBarLayoutParams);


        Last on page change of the view pager updated the RecyclerView on the behavior



        private ViewPager.OnPageChangeListener pageChangeListener = new ViewPager.OnPageChangeListener() 
        @Override
        public void onPageScrolled(int position, float positionOffset, int positionOffsetPixels)

        @Override
        public void onPageSelected(final int position)
        appBarLayout.setExpanded(true, true);
        appBarLayout.post(new Runnable()
        @Override
        public void run()
        appBarBehavior.setRecyclerView(childFragments.get(position).getRecyclerView());

        );


        @Override
        public void onPageScrollStateChanged(int state)
        ;


        This should work with changing datasets.






        share|improve this answer

























        • Really interesting. Thanks for sharing.

          – Paolo Rotolo
          Oct 3 '15 at 13:39











        • Oh also you need to reset the recyclerview on rotation keeping in mind that the view pager give index 0 after being restored even if its not really on that page. Fragments are a joy.

          – Stuart Campbell
          Oct 3 '15 at 14:02















        3














        I took a slightly different approach to solve this.



        I created a custom AppBarBehavior that disables its self based on cells.



        public class CustomAppBarBehavior extends AppBarLayout.Behavior 

        private RecyclerView recyclerView;
        private boolean enabled;

        public CustomAppBarBehavior()


        public CustomAppBarBehavior(Context context, AttributeSet attrs)
        super(context, attrs);


        @Override
        public boolean onInterceptTouchEvent(CoordinatorLayout parent, AppBarLayout child, MotionEvent ev)
        updatedEnabled();
        return enabled && super.onInterceptTouchEvent(parent, child, ev);


        @Override
        public boolean onStartNestedScroll(CoordinatorLayout parent, AppBarLayout child, View directTargetChild, View target, int nestedScrollAxes)
        return enabled && super.onStartNestedScroll(parent, child, directTargetChild, target, nestedScrollAxes);


        @Override
        public boolean onNestedFling(CoordinatorLayout coordinatorLayout, AppBarLayout child, View target, float velocityX, float velocityY, boolean consumed)
        return enabled && super.onNestedFling(coordinatorLayout, child, target, velocityX, velocityY, consumed);


        private void updatedEnabled()
        enabled = false;
        if(recyclerView != null)
        RecyclerView.Adapter adapter = recyclerView.getAdapter();
        if (adapter != null)
        int count = adapter.getItemCount();
        RecyclerView.LayoutManager layoutManager = recyclerView.getLayoutManager();
        if (layoutManager != null)
        int lastItem = 0;
        if (layoutManager instanceof LinearLayoutManager)
        LinearLayoutManager linearLayoutManager = (LinearLayoutManager) layoutManager;
        lastItem = Math.abs(linearLayoutManager.findLastCompletelyVisibleItemPosition());
        else if (layoutManager instanceof StaggeredGridLayoutManager)
        StaggeredGridLayoutManager staggeredGridLayoutManager = (StaggeredGridLayoutManager) layoutManager;
        int lastItems = staggeredGridLayoutManager.findLastCompletelyVisibleItemPositions(new int[staggeredGridLayoutManager.getSpanCount()]);
        lastItem = Math.abs(lastItems[lastItems.length - 1]);

        enabled = lastItem < count - 1;





        public void setRecyclerView(RecyclerView recyclerView)
        this.recyclerView = recyclerView;




        Then set the custom behavior on the app bar layout



        appBarBehavior = new CustomAppBarBehavior();
        CoordinatorLayout.LayoutParams appBarLayoutParams = (CoordinatorLayout.LayoutParams) appBarLayout.getLayoutParams();
        appBarLayoutParams.setBehavior(appBarBehavior);
        appBarLayout.setLayoutParams(appBarLayoutParams);


        Last on page change of the view pager updated the RecyclerView on the behavior



        private ViewPager.OnPageChangeListener pageChangeListener = new ViewPager.OnPageChangeListener() 
        @Override
        public void onPageScrolled(int position, float positionOffset, int positionOffsetPixels)

        @Override
        public void onPageSelected(final int position)
        appBarLayout.setExpanded(true, true);
        appBarLayout.post(new Runnable()
        @Override
        public void run()
        appBarBehavior.setRecyclerView(childFragments.get(position).getRecyclerView());

        );


        @Override
        public void onPageScrollStateChanged(int state)
        ;


        This should work with changing datasets.






        share|improve this answer

























        • Really interesting. Thanks for sharing.

          – Paolo Rotolo
          Oct 3 '15 at 13:39











        • Oh also you need to reset the recyclerview on rotation keeping in mind that the view pager give index 0 after being restored even if its not really on that page. Fragments are a joy.

          – Stuart Campbell
          Oct 3 '15 at 14:02













        3












        3








        3







        I took a slightly different approach to solve this.



        I created a custom AppBarBehavior that disables its self based on cells.



        public class CustomAppBarBehavior extends AppBarLayout.Behavior 

        private RecyclerView recyclerView;
        private boolean enabled;

        public CustomAppBarBehavior()


        public CustomAppBarBehavior(Context context, AttributeSet attrs)
        super(context, attrs);


        @Override
        public boolean onInterceptTouchEvent(CoordinatorLayout parent, AppBarLayout child, MotionEvent ev)
        updatedEnabled();
        return enabled && super.onInterceptTouchEvent(parent, child, ev);


        @Override
        public boolean onStartNestedScroll(CoordinatorLayout parent, AppBarLayout child, View directTargetChild, View target, int nestedScrollAxes)
        return enabled && super.onStartNestedScroll(parent, child, directTargetChild, target, nestedScrollAxes);


        @Override
        public boolean onNestedFling(CoordinatorLayout coordinatorLayout, AppBarLayout child, View target, float velocityX, float velocityY, boolean consumed)
        return enabled && super.onNestedFling(coordinatorLayout, child, target, velocityX, velocityY, consumed);


        private void updatedEnabled()
        enabled = false;
        if(recyclerView != null)
        RecyclerView.Adapter adapter = recyclerView.getAdapter();
        if (adapter != null)
        int count = adapter.getItemCount();
        RecyclerView.LayoutManager layoutManager = recyclerView.getLayoutManager();
        if (layoutManager != null)
        int lastItem = 0;
        if (layoutManager instanceof LinearLayoutManager)
        LinearLayoutManager linearLayoutManager = (LinearLayoutManager) layoutManager;
        lastItem = Math.abs(linearLayoutManager.findLastCompletelyVisibleItemPosition());
        else if (layoutManager instanceof StaggeredGridLayoutManager)
        StaggeredGridLayoutManager staggeredGridLayoutManager = (StaggeredGridLayoutManager) layoutManager;
        int lastItems = staggeredGridLayoutManager.findLastCompletelyVisibleItemPositions(new int[staggeredGridLayoutManager.getSpanCount()]);
        lastItem = Math.abs(lastItems[lastItems.length - 1]);

        enabled = lastItem < count - 1;





        public void setRecyclerView(RecyclerView recyclerView)
        this.recyclerView = recyclerView;




        Then set the custom behavior on the app bar layout



        appBarBehavior = new CustomAppBarBehavior();
        CoordinatorLayout.LayoutParams appBarLayoutParams = (CoordinatorLayout.LayoutParams) appBarLayout.getLayoutParams();
        appBarLayoutParams.setBehavior(appBarBehavior);
        appBarLayout.setLayoutParams(appBarLayoutParams);


        Last on page change of the view pager updated the RecyclerView on the behavior



        private ViewPager.OnPageChangeListener pageChangeListener = new ViewPager.OnPageChangeListener() 
        @Override
        public void onPageScrolled(int position, float positionOffset, int positionOffsetPixels)

        @Override
        public void onPageSelected(final int position)
        appBarLayout.setExpanded(true, true);
        appBarLayout.post(new Runnable()
        @Override
        public void run()
        appBarBehavior.setRecyclerView(childFragments.get(position).getRecyclerView());

        );


        @Override
        public void onPageScrollStateChanged(int state)
        ;


        This should work with changing datasets.






        share|improve this answer















        I took a slightly different approach to solve this.



        I created a custom AppBarBehavior that disables its self based on cells.



        public class CustomAppBarBehavior extends AppBarLayout.Behavior 

        private RecyclerView recyclerView;
        private boolean enabled;

        public CustomAppBarBehavior()


        public CustomAppBarBehavior(Context context, AttributeSet attrs)
        super(context, attrs);


        @Override
        public boolean onInterceptTouchEvent(CoordinatorLayout parent, AppBarLayout child, MotionEvent ev)
        updatedEnabled();
        return enabled && super.onInterceptTouchEvent(parent, child, ev);


        @Override
        public boolean onStartNestedScroll(CoordinatorLayout parent, AppBarLayout child, View directTargetChild, View target, int nestedScrollAxes)
        return enabled && super.onStartNestedScroll(parent, child, directTargetChild, target, nestedScrollAxes);


        @Override
        public boolean onNestedFling(CoordinatorLayout coordinatorLayout, AppBarLayout child, View target, float velocityX, float velocityY, boolean consumed)
        return enabled && super.onNestedFling(coordinatorLayout, child, target, velocityX, velocityY, consumed);


        private void updatedEnabled()
        enabled = false;
        if(recyclerView != null)
        RecyclerView.Adapter adapter = recyclerView.getAdapter();
        if (adapter != null)
        int count = adapter.getItemCount();
        RecyclerView.LayoutManager layoutManager = recyclerView.getLayoutManager();
        if (layoutManager != null)
        int lastItem = 0;
        if (layoutManager instanceof LinearLayoutManager)
        LinearLayoutManager linearLayoutManager = (LinearLayoutManager) layoutManager;
        lastItem = Math.abs(linearLayoutManager.findLastCompletelyVisibleItemPosition());
        else if (layoutManager instanceof StaggeredGridLayoutManager)
        StaggeredGridLayoutManager staggeredGridLayoutManager = (StaggeredGridLayoutManager) layoutManager;
        int lastItems = staggeredGridLayoutManager.findLastCompletelyVisibleItemPositions(new int[staggeredGridLayoutManager.getSpanCount()]);
        lastItem = Math.abs(lastItems[lastItems.length - 1]);

        enabled = lastItem < count - 1;





        public void setRecyclerView(RecyclerView recyclerView)
        this.recyclerView = recyclerView;




        Then set the custom behavior on the app bar layout



        appBarBehavior = new CustomAppBarBehavior();
        CoordinatorLayout.LayoutParams appBarLayoutParams = (CoordinatorLayout.LayoutParams) appBarLayout.getLayoutParams();
        appBarLayoutParams.setBehavior(appBarBehavior);
        appBarLayout.setLayoutParams(appBarLayoutParams);


        Last on page change of the view pager updated the RecyclerView on the behavior



        private ViewPager.OnPageChangeListener pageChangeListener = new ViewPager.OnPageChangeListener() 
        @Override
        public void onPageScrolled(int position, float positionOffset, int positionOffsetPixels)

        @Override
        public void onPageSelected(final int position)
        appBarLayout.setExpanded(true, true);
        appBarLayout.post(new Runnable()
        @Override
        public void run()
        appBarBehavior.setRecyclerView(childFragments.get(position).getRecyclerView());

        );


        @Override
        public void onPageScrollStateChanged(int state)
        ;


        This should work with changing datasets.







        share|improve this answer














        share|improve this answer



        share|improve this answer








        edited Oct 5 '15 at 15:00

























        answered Oct 3 '15 at 13:37









        Stuart CampbellStuart Campbell

        660710




        660710












        • Really interesting. Thanks for sharing.

          – Paolo Rotolo
          Oct 3 '15 at 13:39











        • Oh also you need to reset the recyclerview on rotation keeping in mind that the view pager give index 0 after being restored even if its not really on that page. Fragments are a joy.

          – Stuart Campbell
          Oct 3 '15 at 14:02

















        • Really interesting. Thanks for sharing.

          – Paolo Rotolo
          Oct 3 '15 at 13:39











        • Oh also you need to reset the recyclerview on rotation keeping in mind that the view pager give index 0 after being restored even if its not really on that page. Fragments are a joy.

          – Stuart Campbell
          Oct 3 '15 at 14:02
















        Really interesting. Thanks for sharing.

        – Paolo Rotolo
        Oct 3 '15 at 13:39





        Really interesting. Thanks for sharing.

        – Paolo Rotolo
        Oct 3 '15 at 13:39













        Oh also you need to reset the recyclerview on rotation keeping in mind that the view pager give index 0 after being restored even if its not really on that page. Fragments are a joy.

        – Stuart Campbell
        Oct 3 '15 at 14:02





        Oh also you need to reset the recyclerview on rotation keeping in mind that the view pager give index 0 after being restored even if its not really on that page. Fragments are a joy.

        – Stuart Campbell
        Oct 3 '15 at 14:02











        1














        Add this code after you change data in your adapter:



        recyclerView.afterMeasured 
        val isTurnedOff = recyclerView.turnOffNestedScrollingIfEnoughItems()
        if (isTurnedOff) appBarLayout.setExpanded(true)



        And this is the functions:



        inline fun <T: View> T.afterMeasured(crossinline action: T.() -> Unit) 
        viewTreeObserver.addOnGlobalLayoutListener(object : ViewTreeObserver.OnGlobalLayoutListener
        override fun onGlobalLayout()
        viewTreeObserver.removeOnGlobalLayoutListener(this)
        action()

        )



        fun RecyclerView.turnOffNestedScrollingIfEnoughItems(): Boolean
        val lm = (layoutManager as LinearLayoutManager)
        val count = if (lm.itemCount <= 0) 0 else lm.itemCount - 1
        val isFirstVisible = lm.findFirstCompletelyVisibleItemPosition() == 0
        val isLastItemVisible = lm.findLastCompletelyVisibleItemPosition() == count

        isNestedScrollingEnabled = !(isLastItemVisible && isFirstVisible)
        return isNestedScrollingEnabled.not()






        share|improve this answer





























          1














          Add this code after you change data in your adapter:



          recyclerView.afterMeasured 
          val isTurnedOff = recyclerView.turnOffNestedScrollingIfEnoughItems()
          if (isTurnedOff) appBarLayout.setExpanded(true)



          And this is the functions:



          inline fun <T: View> T.afterMeasured(crossinline action: T.() -> Unit) 
          viewTreeObserver.addOnGlobalLayoutListener(object : ViewTreeObserver.OnGlobalLayoutListener
          override fun onGlobalLayout()
          viewTreeObserver.removeOnGlobalLayoutListener(this)
          action()

          )



          fun RecyclerView.turnOffNestedScrollingIfEnoughItems(): Boolean
          val lm = (layoutManager as LinearLayoutManager)
          val count = if (lm.itemCount <= 0) 0 else lm.itemCount - 1
          val isFirstVisible = lm.findFirstCompletelyVisibleItemPosition() == 0
          val isLastItemVisible = lm.findLastCompletelyVisibleItemPosition() == count

          isNestedScrollingEnabled = !(isLastItemVisible && isFirstVisible)
          return isNestedScrollingEnabled.not()






          share|improve this answer



























            1












            1








            1







            Add this code after you change data in your adapter:



            recyclerView.afterMeasured 
            val isTurnedOff = recyclerView.turnOffNestedScrollingIfEnoughItems()
            if (isTurnedOff) appBarLayout.setExpanded(true)



            And this is the functions:



            inline fun <T: View> T.afterMeasured(crossinline action: T.() -> Unit) 
            viewTreeObserver.addOnGlobalLayoutListener(object : ViewTreeObserver.OnGlobalLayoutListener
            override fun onGlobalLayout()
            viewTreeObserver.removeOnGlobalLayoutListener(this)
            action()

            )



            fun RecyclerView.turnOffNestedScrollingIfEnoughItems(): Boolean
            val lm = (layoutManager as LinearLayoutManager)
            val count = if (lm.itemCount <= 0) 0 else lm.itemCount - 1
            val isFirstVisible = lm.findFirstCompletelyVisibleItemPosition() == 0
            val isLastItemVisible = lm.findLastCompletelyVisibleItemPosition() == count

            isNestedScrollingEnabled = !(isLastItemVisible && isFirstVisible)
            return isNestedScrollingEnabled.not()






            share|improve this answer















            Add this code after you change data in your adapter:



            recyclerView.afterMeasured 
            val isTurnedOff = recyclerView.turnOffNestedScrollingIfEnoughItems()
            if (isTurnedOff) appBarLayout.setExpanded(true)



            And this is the functions:



            inline fun <T: View> T.afterMeasured(crossinline action: T.() -> Unit) 
            viewTreeObserver.addOnGlobalLayoutListener(object : ViewTreeObserver.OnGlobalLayoutListener
            override fun onGlobalLayout()
            viewTreeObserver.removeOnGlobalLayoutListener(this)
            action()

            )



            fun RecyclerView.turnOffNestedScrollingIfEnoughItems(): Boolean
            val lm = (layoutManager as LinearLayoutManager)
            val count = if (lm.itemCount <= 0) 0 else lm.itemCount - 1
            val isFirstVisible = lm.findFirstCompletelyVisibleItemPosition() == 0
            val isLastItemVisible = lm.findLastCompletelyVisibleItemPosition() == count

            isNestedScrollingEnabled = !(isLastItemVisible && isFirstVisible)
            return isNestedScrollingEnabled.not()







            share|improve this answer














            share|improve this answer



            share|improve this answer








            edited Jul 6 '18 at 19:05

























            answered Jul 5 '18 at 17:02









            Artur DumchevArtur Dumchev

            334313




            334313





















                -1














                You can add within your XML, the property layout_behaviour with value @string/appbar_scrolling_view_behavior this way:



                app:layout_behavior="@string/appbar_scrolling_view_behavior"





                share|improve this answer





























                  -1














                  You can add within your XML, the property layout_behaviour with value @string/appbar_scrolling_view_behavior this way:



                  app:layout_behavior="@string/appbar_scrolling_view_behavior"





                  share|improve this answer



























                    -1












                    -1








                    -1







                    You can add within your XML, the property layout_behaviour with value @string/appbar_scrolling_view_behavior this way:



                    app:layout_behavior="@string/appbar_scrolling_view_behavior"





                    share|improve this answer















                    You can add within your XML, the property layout_behaviour with value @string/appbar_scrolling_view_behavior this way:



                    app:layout_behavior="@string/appbar_scrolling_view_behavior"






                    share|improve this answer














                    share|improve this answer



                    share|improve this answer








                    edited Nov 15 '18 at 7:16









                    gratien asimbahwe

                    1,11931123




                    1,11931123










                    answered Nov 15 '18 at 6:26









                    Kumar SunnyKumar Sunny

                    11




                    11





















                        -2














                        //turn off scrolling
                        AppBarLayout.LayoutParams toolbarLayoutParams = (AppBarLayout.LayoutParams) mToolbar.getLayoutParams();
                        toolbarLayoutParams.setScrollFlags(0);
                        mToolbar.setLayoutParams(toolbarLayoutParams);





                        share|improve this answer





























                          -2














                          //turn off scrolling
                          AppBarLayout.LayoutParams toolbarLayoutParams = (AppBarLayout.LayoutParams) mToolbar.getLayoutParams();
                          toolbarLayoutParams.setScrollFlags(0);
                          mToolbar.setLayoutParams(toolbarLayoutParams);





                          share|improve this answer



























                            -2












                            -2








                            -2







                            //turn off scrolling
                            AppBarLayout.LayoutParams toolbarLayoutParams = (AppBarLayout.LayoutParams) mToolbar.getLayoutParams();
                            toolbarLayoutParams.setScrollFlags(0);
                            mToolbar.setLayoutParams(toolbarLayoutParams);





                            share|improve this answer















                            //turn off scrolling
                            AppBarLayout.LayoutParams toolbarLayoutParams = (AppBarLayout.LayoutParams) mToolbar.getLayoutParams();
                            toolbarLayoutParams.setScrollFlags(0);
                            mToolbar.setLayoutParams(toolbarLayoutParams);






                            share|improve this answer














                            share|improve this answer



                            share|improve this answer








                            edited Sep 21 '15 at 16:12









                            hata

                            4,92731944




                            4,92731944










                            answered Sep 21 '15 at 16:06









                            Kalpesh SevakKalpesh Sevak

                            11




                            11





















                                -2














                                Just remove scroll from



                                app:layout_scrollFlags="scroll|enterAlways"


                                So it should be



                                app:layout_scrollFlags="enterAlways"





                                share|improve this answer


















                                • 4





                                  This totally locks the CollapsingToolbarLayout from scrolling...

                                  – Rafal Zawadzki
                                  Jun 9 '17 at 14:51















                                -2














                                Just remove scroll from



                                app:layout_scrollFlags="scroll|enterAlways"


                                So it should be



                                app:layout_scrollFlags="enterAlways"





                                share|improve this answer


















                                • 4





                                  This totally locks the CollapsingToolbarLayout from scrolling...

                                  – Rafal Zawadzki
                                  Jun 9 '17 at 14:51













                                -2












                                -2








                                -2







                                Just remove scroll from



                                app:layout_scrollFlags="scroll|enterAlways"


                                So it should be



                                app:layout_scrollFlags="enterAlways"





                                share|improve this answer













                                Just remove scroll from



                                app:layout_scrollFlags="scroll|enterAlways"


                                So it should be



                                app:layout_scrollFlags="enterAlways"






                                share|improve this answer












                                share|improve this answer



                                share|improve this answer










                                answered Apr 2 '17 at 21:51









                                Waran-Waran-

                                81221122




                                81221122







                                • 4





                                  This totally locks the CollapsingToolbarLayout from scrolling...

                                  – Rafal Zawadzki
                                  Jun 9 '17 at 14:51












                                • 4





                                  This totally locks the CollapsingToolbarLayout from scrolling...

                                  – Rafal Zawadzki
                                  Jun 9 '17 at 14:51







                                4




                                4





                                This totally locks the CollapsingToolbarLayout from scrolling...

                                – Rafal Zawadzki
                                Jun 9 '17 at 14:51





                                This totally locks the CollapsingToolbarLayout from scrolling...

                                – Rafal Zawadzki
                                Jun 9 '17 at 14:51

















                                draft saved

                                draft discarded
















































                                Thanks for contributing an answer to Stack Overflow!


                                • Please be sure to answer the question. Provide details and share your research!

                                But avoid


                                • Asking for help, clarification, or responding to other answers.

                                • Making statements based on opinion; back them up with references or personal experience.

                                To learn more, see our tips on writing great answers.




                                draft saved


                                draft discarded














                                StackExchange.ready(
                                function ()
                                StackExchange.openid.initPostLogin('.new-post-login', 'https%3a%2f%2fstackoverflow.com%2fquestions%2f32404979%2fdont-collapse-toolbar-when-recyclerview-fits-the-screen%23new-answer', 'question_page');

                                );

                                Post as a guest















                                Required, but never shown





















































                                Required, but never shown














                                Required, but never shown












                                Required, but never shown







                                Required, but never shown

































                                Required, but never shown














                                Required, but never shown












                                Required, but never shown







                                Required, but never shown







                                這個網誌中的熱門文章

                                How to read a connectionString WITH PROVIDER in .NET Core?

                                Node.js Script on GitHub Pages or Amazon S3

                                Museum of Modern and Contemporary Art of Trento and Rovereto