4

我正在使用Activity类(通常)一个片段作为内容。在活动中,我使用CollapsingToolbarLayout作为某种信息的头部,一切正常。但在某些情况下(当附加一些片段时),我不想显示该信息,我不想在滚动上打开CollapsingToolbarLayout如何从Android支持库锁定CollapsingToolbarLayout

我想实现的是锁住CollapsingToolbarLayout,防止它从碎片中打开。我以编程方式崩溃它appBarLayout.setExpanded(false, true);

回答

3

嗯,我设法自己解决它。诀窍是禁用嵌套滚动行为ViewCompat.setNestedScrollingEnabled(recyclerView, expanded);

因为我在活动中使用一个片段作为内容视图并将其放置在后台堆栈上,我只需检查backstack何时发生更改以及哪个片段是可见的。请注意,我在每个片段的NestedScrollView中触发可折叠的工具栏。这是我的代码:

getSupportFragmentManager().addOnBackStackChangedListener(new FragmentManager.OnBackStackChangedListener() { 
     @Override 
     public void onBackStackChanged() { 
      NestedScrollView nestedScrollView = (NestedScrollView)findViewById(R.id.nested_scroll_view); 
      int size = getSupportFragmentManager().getBackStackEntryCount(); 
      if (size >= 1 && nestedScrollView != null) { 
       if (getSupportFragmentManager().getBackStackEntryAt(size - 1).getName().equals("SpotDetailsFragment")) { 
        Log.d(LOG_TAG, "Enabling collapsible toolbar."); 
        ViewCompat.setNestedScrollingEnabled(nestedScrollView, true); 
       } else { 
        Log.d(LOG_TAG, "Disabling collapsible toolbar."); 
        ViewCompat.setNestedScrollingEnabled(nestedScrollView, false); 
       } 
      } 
     } 
    }); 

这个线程帮了我很多,在另一种可能的解决方案提出: Need to disable expand on CollapsingToolbarLayout for certain fragments

3

我想出了一个不同的方法设置嵌套滚动标志仅拖动时工作NestedScrollView。应用栏仍然可以通过在栏上自行刷新来扩展。

我把它设置为“Utils”类中的一个静态函数。显然,解锁时设置的标志取决于哪些标志与您的用例相关。

此功能假定您开始用展开的工具栏

public static void LockToolbar(boolean locked, final AppBarLayout appbar, final CollapsingToolbarLayout toolbar) { 

    if (locked) { 
     // We want to lock so add the listener and collapse the toolbar 
     appbar.addOnOffsetChangedListener(new AppBarLayout.OnOffsetChangedListener() { 

      @Override 
      public void onOffsetChanged(AppBarLayout appBarLayout, int verticalOffset) { 
       if (toolbar.getHeight() + verticalOffset < 2 * ViewCompat.getMinimumHeight(toolbar)) { 
        // Now fully expanded again so remove the listener 
        appbar.removeOnOffsetChangedListener(this); 
       } else { 
        // Fully collapsed so set the flags to lock the toolbar 
        AppBarLayout.LayoutParams lp = (AppBarLayout.LayoutParams) toolbar.getLayoutParams(); 
        lp.setScrollFlags(AppBarLayout.LayoutParams.SCROLL_FLAG_ENTER_ALWAYS_COLLAPSED); 
       } 
      } 
     }); 
     appbar.setExpanded(false, true); 
    } else { 
     // Unlock by restoring the flags and then expand 
     AppBarLayout.LayoutParams lp = (AppBarLayout.LayoutParams) toolbar.getLayoutParams(); 
     lp.setScrollFlags(AppBarLayout.LayoutParams.SCROLL_FLAG_SCROLL | AppBarLayout.LayoutParams.SCROLL_FLAG_EXIT_UNTIL_COLLAPSED); 
     appbar.setExpanded(true, true); 
    } 

} 
+0

你为什么在回答我的答案张贴随机码?由于我的答案没有使用任何数组,并且您的代码是由数组生成的异常,所以它们没有任何相关性。 – Kuffs

+1

注意!不要忘记打电话给这条线: toolbar.setLayoutParams(lp); 否则解决方法不起作用。 – maXp