如何通过触摸外部抽屉来防止关闭导航抽屉

如何通过触摸外部抽屉来防止关闭导航抽屉

本文介绍了如何通过触摸外部抽屉来防止关闭导航抽屉的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个带有导航抽屉的活动.如果用户设备是桌子,方向是横向-我不需要通过单击抽屉中的项目来关闭抽屉:

I have an Activity with Navigation Drawer. if user device is table and orientation is landscape - I not need to close drawer by click on item in drawer:

if (!isTablet || context.getResources().getConfiguration().orientation==1) {
    mDrawerLayout.closeDrawer(Gravity.START);
}

有效.但是,如果用户在打开的抽屉外面触摸屏幕-抽屉关闭.不适合使用DrawerLayout.LOCK_MODE_LOCKED_OPEN,因为我需要保存抽屉滑动功能.如何在用户触摸抽屉外部时防止其关闭导航抽屉?

It work. But if user touch the screen outside opened drawer - drawer closing.Using DrawerLayout.LOCK_MODE_LOCKED_OPEN is unsuitable bacause I need to save drawer sliding functions.How to prevent closing Navigation drawer when user touch outside the drawer?

请帮助.

推荐答案

基于我在在此处写的另一个答案.我已经修改了代码以适合您的问题.请检查.

Based on the other answer which I wrote here. I have modified the code to suit your question. Please check.

此处

dispatchTouchEvent()方法应在Activity类中覆盖

@Override
public boolean dispatchTouchEvent(MotionEvent event) {
    if (event.getAction() == MotionEvent.ACTION_UP) {
        if (isDrawerOpen()) { //Your code here to check whether drawer is open or not.

            View content = findViewById(R.id.drawer); //drawer view id
            int[] contentLocation = new int[2];
            content.getLocationOnScreen(contentLocation);
            Rect rect = new Rect(contentLocation[0],
                contentLocation[1],
                contentLocation[0] + content.getWidth(),
                contentLocation[1] + content.getHeight());

            if (!(rect.contains((int) event.getX(), (int) event.getY()))) {
                isOutSideClicked = true;
            } else {
                isOutSideClicked = false;
            }

        } else {
            return super.dispatchTouchEvent(event);
        }
    } else if (event.getAction() == MotionEvent.ACTION_DOWN && isOutSideClicked) {
        isOutSideClicked = false;
        return super.dispatchTouchEvent(event);
    } else if (event.getAction() == MotionEvent.ACTION_MOVE && isOutSideClicked) {
        return super.dispatchTouchEvent(event);
    }

    if (isOutSideClicked) {
        return true; //restrict the touch event here
    }else{
        return super.dispatchTouchEvent(event);
    }
}

注意:如问题注释中所述,这与 Android指南.因此,除非有强制性要求,否则请尽量避免使用它.

Note: As mentioned in the question comments, this is against of Android guidelines. So try to avoid it until unless it is mandatory.

这篇关于如何通过触摸外部抽屉来防止关闭导航抽屉的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!

08-19 21:44