anddev
anddev

Reputation: 3204

How to handle Back button while using DrawerLayout in activity in android?

I am using DrawerLayout in my application. Now when I pressed on back button first of all it is closing DrawerLayout and need to click again on back button then it will redirect to previous screen.

But I want to avoid this DrawerLayout closing on back button. Can anyone know how to prevent this?

Please suggest me the way I am stuck on this.

Thanks in advance.

Upvotes: 0

Views: 4112

Answers (5)

AshuKingSharma
AshuKingSharma

Reputation: 757

use

@Override
    public void onBackPressed() {
        // TODO Auto-generated method stub
        super.onBackPressed();
    }

or simply call super.onBackPressed() in keydown event.

Upvotes: 0

BladeCoder
BladeCoder

Reputation: 12929

Just make the drawer non focusable and it will not intercept the back button anymore:

mDrawerLayout.setFocusable(false);

Upvotes: 4

Abi-
Abi-

Reputation: 301

DrawerLayout intercepts default onKeyDown and onKeyUp so just create new class extended from DrawerLayout and Override this methods

something like this:

import android.content.Context;
import android.support.v4.widget.DrawerLayout;
import android.util.AttributeSet;
import android.view.KeyEvent;

public class MyDrawerLayout extends DrawerLayout {

    public MyDrawerLayout(Context context, AttributeSet attrs, int defStyle) {
        super(context, attrs, defStyle);
    }

    public MyDrawerLayout(Context context, AttributeSet attrs) {
        super(context, attrs);
    }

    public MyDrawerLayout(Context context) {
        super(context);
    }

    @Override
    public boolean onKeyUp(int keyCode, KeyEvent event) {
        if (keyCode == KeyEvent.KEYCODE_BACK) {
            return false;
        }
        return super.onKeyUp(keyCode, event);
    }

    @Override
    public boolean onKeyDown(int keyCode, KeyEvent event) {
        if (keyCode == KeyEvent.KEYCODE_BACK) {
            return false;
        }
        return super.onKeyDown(keyCode, event);
    }   
}

Upvotes: 5

jyomin
jyomin

Reputation: 1967

Use the finish() function on the click of the back button

Upvotes: -2

Shivang Trivedi
Shivang Trivedi

Reputation: 2182

try this for Slide Activity u can easyle handle back key : https://github.com/jfeinstein10/SlidingMenu

Upvotes: 0

Related Questions