有多种方法可以实现上滑抽屉,以下是其中一种方式:

  1. 在布局文件中定义一个线性布局,将其设置为隐藏,并设置其高度为0dp。
<LinearLayout
    android:id='@+id/bottom_sheet'
    android:layout_width='match_parent'
    android:layout_height='0dp'
    android:orientation='vertical'
    android:background='@android:color/white'
    android:elevation='8dp'
    android:visibility='gone'
    >
    <!-- 在这里添加抽屉内容 -->
</LinearLayout>
  1. 在Activity中,定义一个变量来保存布局文件中的LinearLayout对象,并使用GestureDetector类来检测手势。
public class MainActivity extends AppCompatActivity implements GestureDetector.OnGestureListener {

    private GestureDetectorCompat gestureDetector;
    private LinearLayout bottomSheet;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);

        bottomSheet = findViewById(R.id.bottom_sheet);
        gestureDetector = new GestureDetectorCompat(this, this);
    }

    @Override
    public boolean onTouchEvent(MotionEvent event) {
        gestureDetector.onTouchEvent(event);
        return super.onTouchEvent(event);
    }

    @Override
    public boolean onDown(MotionEvent e) {
        return true;
    }

    @Override
    public boolean onFling(MotionEvent e1, MotionEvent e2, float velocityX, float velocityY) {
        if (e2.getY() - e1.getY() > 100 && Math.abs(velocityY) > 100) {
            showBottomSheet();
            return true;
        } else if (e1.getY() - e2.getY() > 100 && Math.abs(velocityY) > 100) {
            hideBottomSheet();
            return true;
        }
        return false;
    }

    @Override
    public void onLongPress(MotionEvent e) {}

    @Override
    public boolean onScroll(MotionEvent e1, MotionEvent e2, float distanceX, float distanceY) {
        return false;
    }

    @Override
    public void onShowPress(MotionEvent e) {}

    @Override
    public boolean onSingleTapUp(MotionEvent e) {
        return false;
    }

    private void showBottomSheet() {
        bottomSheet.setVisibility(View.VISIBLE);
        bottomSheet.animate().translationY(0).setDuration(500).start();
    }

    private void hideBottomSheet() {
        bottomSheet.animate().translationY(bottomSheet.getHeight()).setDuration(500).withEndAction(new Runnable() {
            @Override
            public void run() {
                bottomSheet.setVisibility(View.GONE);
            }
        }).start();
    }
}
  1. 在onFling()方法中检测手势,如果检测到向上滑动,则调用showBottomSheet()方法来显示抽屉,如果检测到向下滑动,则调用hideBottomSheet()方法来隐藏抽屉。

这种方法的效果类似于BottomSheetDialog,但是没有使用DrawerLayout,而是使用了手势检测来实现上滑抽屉的效果。

Android 自定义上滑抽屉:不使用 DrawerLayout 和 BottomSheetDialog

原文地址: http://www.cveoy.top/t/topic/oFTK 著作权归作者所有。请勿转载和采集!

免费AI点我,无需注册和登录