如何在没有操作栏的情况下打开导航抽屉,只需一个按钮即可打开 [英] How to open Navigation Drawer with no actionbar, open with just a button

查看:33
本文介绍了如何在没有操作栏的情况下打开导航抽屉,只需一个按钮即可打开的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个没有任何操作栏的导航栏(我不想要一个操作栏).我正在努力使我有一个可以打开导航抽屉的按钮.

I have a navigation bar without any actionbar (I don't want an actionbar). I'm trying to make it so that I have a button that can open the navigation drawer.

我知道 DrawerLayout 有一个叫做 openDrawer 的方法http://developer.android.com/reference/android/support/v4/widget/DrawerLayout.html#openDrawer(android.view.View)

I know there's a method called openDrawer for the DrawerLayout http://developer.android.com/reference/android/support/v4/widget/DrawerLayout.html#openDrawer(android.view.View)

我不知道如何使用它,但我尝试在点击时制作一个按钮,运行此方法:

I didn't know how to use it, but i have tried making a button when click, runs this method:

DrawerLayout mDrawerLayout = (DrawerLayout) getView().findViewById(R.id.drawer_layout);
mDrawerLayout.openDrawer(mDrawerLayout);

当我点击它时,它给了我一个 Java NullPointerException.有人有什么想法吗?

When i click it on it, it gives me a Java NullPointerException. Anybody has any idea?

这段代码在一个片段内,我试图在片段外引用那些抽屉布局.我使用了调试器,它显示 mDrawlerLayout 为 NULL.

This code is inside a fragment, and I'm trying to refer those drawer layout outside the fragment. I used debugger, and it is showing that mDrawlerLayout is NULL.

有什么建议吗?

谢谢!

推荐答案

它给了你一个空指针,因为你试图在片段的视图中找到抽屉布局,而实际上它在活动视图中.

It's giving you a null pointer because you are trying to find the drawer layout in the fragment's view, when it is actually in the activities view.

做你想做的一个快速黑客是找到这样的视图:

A quick hack to do what you want is to find the view like:

getActivity().findViewById(R.id.drawer_layout)

应该可以.更好的方法是在Activity上有一个打开抽屉的方法

That should work. A better way is to have a method on the activity for opening the drawer

public void openDrawer(){
    mDrawerLayout.openDrawer(mDrawerLayout);
}

在 onCreate 活动中运行您的 findViewById:

In the activity onCreate run your findViewById:

mDrawerLayout = (DrawerLayout) getView().findViewById(R.id.drawer_layout);

mDrawerLayout 应该是您的 Activity 的成员变量.

mDrawerLayout should be a member variable of your activity.

然后在你的片段中你可以调用:

Then in your fragment you can call:

//cast activity to MyActivity so compiler doesn't complain
((MyActivity)getActivity()).openDrawer();

一个更好的方法是在片段中创建一个侦听器并将活动设置为片段的侦听器.然后你可以在活动上调用一个方法,类似于上面的.我会让你研究如何做到这一点.

An even better way to do it is to create a listener in the fragment and set the activity as a listener to the fragment. Then you can call a method on the activity, similar to above. I'll let you do some research on how to do that.

这篇关于如何在没有操作栏的情况下打开导航抽屉,只需一个按钮即可打开的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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