Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
844 views
in Technique[技术] by (71.8m points)

android - How to prevent closing Navigation drawer by touch outside the drawer

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);
}

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?

Please, help.

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

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

Check more about touch hierarchy here

dispatchTouchEvent() method should be overridden in Activity class

@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);
    }
}

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


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...