Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to close Drawer layout on BackPress in Android?

Tags:

android

I press the navigation drawer, then if I press back button, the app exits rather than returning to the previous activity. If I change the xml file, then this problem doesn't occur. So I think the problem is in the xml file. Can anyone tell me what is the problem? Here's the xml code.`

<ImageView
    android:id="@+id/imageView1"
    android:layout_width="500dp"
    android:layout_height="200dp"
    android:layout_alignParentLeft="true"
    android:layout_alignParentTop="true"
    android:src="@drawable/blue_train" />

<TextView
    android:id="@+id/trainName"
    android:layout_width="wrap_content"
    android:layout_height="wrap_content"
    android:layout_alignParentBottom="true"
    android:layout_alignParentLeft="true"
    android:layout_marginBottom="200dp"
    android:layout_marginLeft="14dp"
    android:text="Train Name"
    android:textColor="@color/bluedark"
    android:textSize="15sp" />

<EditText
    android:id="@+id/etName"
    android:layout_width="150dp"
    android:layout_height="40dp"
    android:layout_alignBaseline="@+id/trainName"
    android:layout_alignBottom="@+id/trainName"
    android:layout_marginLeft="30dp"
    android:layout_toRightOf="@+id/trainName"
    android:background="@drawable/line"
    android:ems="10" >

    <requestFocus />
</EditText>

<Button
    android:id="@+id/getS"
    android:layout_width="150dp"
    android:layout_height="wrap_content"
    android:layout_below="@+id/etName"
    android:layout_centerHorizontal="true"
    android:layout_marginTop="40dp"
    android:background="@drawable/button2"
    android:text="Get Train Schedule"
    android:textColor="@color/white" />

`

like image 506
alu Avatar asked Mar 04 '14 21:03

alu


2 Answers

This will close the drawer when it's open and back is pressed rather than taking you back to the previous activity (or exiting).

DrawerLayout drawer...

@Override
public void onBackPressed() {
    // TODO Auto-generated method stub

    if(drawer.isDrawerOpen(Gravity.LEFT)){
        drawer.closeDrawer(Gravity.LEFT);
    }else{
        super.onBackPressed();
    }
}
like image 87
NameSpace Avatar answered Sep 18 '22 13:09

NameSpace


ListView mDrawerList;

@Override
public void onBackPressed() {
// TODO Auto-generated method stub

if(mDrawerLayout.isDrawerOpen(mDrawerList)){
    mDrawerLayout.closeDrawer(mDrawerList);
}else{
    super.onBackPressed();
}
}
like image 40
ultimate Avatar answered Sep 20 '22 13:09

ultimate