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