如何打开抽屉式导航,没有动作条,只需一个按钮开启
我已经没有任何动作条导航栏(我不想要一个动作条)。我试图让这个我有一个按钮,可以打开抽屉式导航。
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.
我知道有一个叫openDrawer的DrawerLayout方法 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?
编辑: 这code是一个片段里面,我想指的抽屉布局的片段之外。我用调试器,它表明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)
这应该工作。更好的办法是有活性的方法打开抽屉
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应该是你活动的成员变量。
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.