如何通过从屏幕的底部边缘拉出来显示BottomSheet?

时间:2017-03-22 03:13:04

标签: android android-layout bottom-sheet

我是Android BottomSheet的新手,我已成功尝试了如何使用它的示例,但大多数示例仅演示通过查看点击事件显示/隐藏BottomSheet 。

现在我有以下代码:

BottomSheetBehavior mBottomSheetBehavior;

@Override
protected void onCreate() {
   super.onCreate(savedInstanceState);
   setContentView(R.layout.activity_main);
   View bottomSheet = findViewById(R.id.bottom_sheet);
   mBottomSheetBehavior = BottomSheetBehavior.from(bottomSheet);
   mBottomSheetBehavior.setPeekHeight(0);
   mBottomSheetBehavior.setState(BottomSheetBehavior.STATE_HIDDEN);
}

现在,我想知道当状态是BottomSheetBehavior.STATE_HIDDEN并且peekHeight是{{1时,是否可以通过从屏幕的底部边缘拉/拖来显示BottomSheet类似于DrawerLayout的行为?

1 个答案:

答案 0 :(得分:1)

我不认为BottomSheetBehavior提供该功能,但您可以拦截包含活动中的触摸事件,并在检测到底部拉动时展开底部工作表:

@Override
protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    bottomPullDetector = new GestureDetectorCompat(this, new BottomPullListener());
}

@Override
public boolean dispatchTouchEvent(MotionEvent ev) {
    return bottomPullDetector.onTouchEvent(ev) || super.dispatchTouchEvent(ev);
}


private class BottomPullListener extends GestureDetector.SimpleOnGestureListener {
    private static final int SWIPE_THRESHOLD = 20;
    private final int displayHeight;
    private boolean beginningOnBottom;

    BottomPullListener() {
        final Point displaySize = new Point();
        getWindowManager().getDefaultDisplay().getSize(displaySize);
        displayHeight = displaySize.y;
    }

    @Override
    public boolean onDown(MotionEvent event) {
        beginningOnBottom = displayHeight - event.getY() < SWIPE_THRESHOLD;
        return beginningOnBottom;
    }

    @Override
    public boolean onFling(MotionEvent e1, MotionEvent e2, float velocityX, float velocityY) {
        if (beginningOnBottom && e1.getY() > e2.getY()) {
            cameraFragment.expandBottomSheet();
            return true;
        }
        return false;
    }
}