Collapsing Toolbar only for one Fragment in Navigation View

前端 未结 5 1029
天命终不由人
天命终不由人 2021-01-02 03:47

The Problem

I have a navigation drawer with different fragments. There is a default toolbar every Fragment should use, except of one Fragment

5条回答
  •  佛祖请我去吃肉
    2021-01-02 04:24

    The best solution that I found to easily collapse, lock it(keep it in collapsed mode) and unlock the collapsingToolbar.

    private void collapseAppBar() {
        // Collapse the AppBarLayout with animation
        mAppBarLayout.setExpanded(false, true);
    }
    
    private void lockAppBar() {
        /* Disable the nestedScrolling to disable expanding the
         appBar with dragging the nestedScrollView below it */
        ViewCompat.setNestedScrollingEnabled(nestedScrollView, false);
    
        /* But still appBar is expandable with dragging the appBar itself
        and below code disables that too
         */
        CoordinatorLayout.LayoutParams params = (CoordinatorLayout.LayoutParams) mAppBarLayout.getLayoutParams();
        AppBarLayout.Behavior behavior = (AppBarLayout.Behavior) params.getBehavior();
        behavior.setDragCallback(new AppBarLayout.Behavior.DragCallback() {
            @Override
            public boolean canDrag(AppBarLayout appBarLayout) {
                return false;
            }
        });
    }
    
    private void unLockAppBar() {
        ViewCompat.setNestedScrollingEnabled(nestedScrollView, true);
    
        CoordinatorLayout.LayoutParams params = (CoordinatorLayout.LayoutParams) mAppBarLayout.getLayoutParams();
        AppBarLayout.Behavior behavior = (AppBarLayout.Behavior) params.getBehavior();
        if (behavior != null) {
            behavior.setDragCallback(new AppBarLayout.Behavior.DragCallback() {
                @Override
                public boolean canDrag(AppBarLayout appBarLayout) {
                    return true;
                }
            });
        }
    }
    

    And I use these functions in this way:

        Fragment fragment = null;
        Class fragmentClass;
        switch (menuItem.getItemId()) {
            case R.id.fragment1:
                unLockAppBar();
                fragmentClass = first_Fragment.class;
                break;
            case R.id.fragment2:
                collapseAppBar();
                lockAppBar();
                fragmentClass = second_Fragment.class;
                break;
            case R.id.fragment3:
                collapseAppBar();
                lockAppBar();
                fragmentClass = third_Fragment.class;
                break;
    

提交回复
热议问题