当用户按下后退按钮时隐藏导航抽屉 [英] Hide navigation drawer when user presses back button

查看:34
本文介绍了当用户按下后退按钮时隐藏导航抽屉的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我已按照 Google 的官方开发者教程此处创建导航抽屉.

I've followed Google's official developer tutorials here to create a navigation drawer.

目前,一切正常,除了用户使用 Android 在屏幕底部提供的本机后退按钮(以及主页和最近的应用程序按钮).如果用户使用本机返回按钮向后导航,导航抽屉仍将打开.如果用户使用 ActionBar 导航回来,导航抽屉将按我想要的方式关闭.

At the moment, everything works fine, except for when the user uses the native back button Android provides at the bottom of the screen (along with the home and recent app buttons). If the user navigates back using this native back button, the navigation drawer will still be open. If the user instead navigates back using the ActionBar, the navigation drawer will be closed like I want it to be.

我的代码与官方教程几乎相同,除了我如何处理用户选择抽屉上的项目:

My code is nearly identical to the official tutorials, except for how I handle the user selecting an item on the drawer:

   mDrawerList.setOnItemClickListener(new ListView.OnItemClickListener()
    {
        @Override
        public void onItemClick(AdapterView parent, View view, int position, long id)
        {
            switch(position)
            {
                case 0:
                {
                    Intent intent = new Intent(MainActivity.this, NextActivity.class);
                    startActivity(intent);
                }
            }
        }
    });

当用户使用本机后退按钮导航返回时,如何关闭导航抽屉?任何建议表示赞赏.谢谢!

How can I have the navigation drawer be closed when the user navigates back using the native back button? Any advice appreciated. Thanks!

推荐答案

你必须重写 onBackPressed().来自文档:

You have to override onBackPressed(). From the docs :

当 Activity 检测到用户按下背部时调用钥匙.默认实现只是完成当前活动,但是你可以覆盖它来做任何你想做的事情.

Called when the activity has detected the user's press of the back key. The default implementation simply finishes the current activity, but you can override this to do whatever you want.

所以你可以有这样的代码:

So you can have code like this :

@Override
public void onBackPressed() {
    if (this.drawerLayout.isDrawerOpen(GravityCompat.START)) {
        this.drawerLayout.closeDrawer(GravityCompat.START);
    } else {
        super.onBackPressed();
    }
}

如果是打开的,这个方法会关闭它,否则回退到默认行为.

If is open this method closes it, else falls back to the default behavior.

这篇关于当用户按下后退按钮时隐藏导航抽屉的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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