Android 底部 Sheet 状态改变后

Android Bottom Sheet after state changed

我有一个带有底页的屏幕,但是为了让过渡动画在活动之间工作,我需要在用户继续按下时折叠底页。我试过这个

@Override
public void onBackPressed(){
    if (mBottomSheetBehavior.getState() == BottomSheetBehavior.STATE_COLLAPSED) {
        super.onBackPressed();
    } else {
        mBottomSheetBehavior.setState(BottomSheetBehavior.STATE_COLLAPSED);
        super.onBackPressed();
    }

    mShowingBack = false;
}

然而,这不起作用,因为 activity 返回,而底纸只下降了一半。

BottomSheetBehavior.STATE_COLLAPSED 不会隐藏所有 BottomSheet,它只是将视图的高度设置为您在 xml 中使用 setPeekHeight() 或 behavior_peekHeight 设置的任何值 :) 但是把那个放在一边...当 BottomSheet 的状态为 STATE_COLLAPSED 时,您应该在 BottomSheetBehaviorCallback 中调用 super.onBackPressed(),如下所示:

BottomSheetBehavior behavior = BottomSheetBehavior.from(mBottomSheetBehavior);  
behavior.addBottomSheetCallback(new BottomSheetCallback() {  
   @Override  
   public void onStateChanged(@NonNull View bottomSheet, int newState) {  
     if (newState == BottomSheetBehavior.STATE_COLLAPSED && mIsCollapsedFromBackPress){
        mIsCollapsedFromBackPress = false;
        super.onBackPressed();
     }
   }  

  @Override  
  public void onSlide(@NonNull View bottomSheet, float slideOffset) {  
     // React to dragging events  
  }  
});

您的 backPressed() 方法应如下所示:

@Override
public void onBackPressed(){
    mIsCollapsedFromBackPress = true;
    mBottomSheetBehavior.setState(BottomSheetBehavior.STATE_COLLAPSED);
}
behavior.setBottomSheetCallback(); 

现已弃用。改用这个。

BottomSheetBehavior.from(nearbyBottomSheet).addBottomSheetCallback(object :BottomSheetBehavior.BottomSheetCallback() {
        override fun onStateChanged(bottomSheet: View, newState: Int) {

        }

        override fun onSlide(bottomSheet: View, slideOffset: Float) {
                
        }
})