如何在Android中的BackPress上关闭Drawer布局? [英] How to close Drawer layout on BackPress in Android?

查看:96
本文介绍了如何在Android中的BackPress上关闭Drawer布局?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我按下导航抽屉,然后如果我按下后退"按钮,则该应用程序退出,而不是返回到上一个活动.如果更改xml文件,则不会发生此问题.所以我认为问题出在xml文件中.谁能告诉我这是什么问题? 这是xml代码.

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" />

`

推荐答案

这将在抽屉打开并关闭后关闭抽屉,而不是使您返回上一个活动(或退出).

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

这篇关于如何在Android中的BackPress上关闭Drawer布局?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆