简体   繁体   English

选择项目后如何关闭导航抽屉?

[英]How do I close a navigation drawer after an item is selected?

I have implemented a navigation drawer and everything functions properly. 我已经实现了一个导航抽屉,并且所有功能均正常运行。 The navigation drawer contains a listview and when an item is selected, the main fragment is replaced properly. 导航抽屉包含一个列表视图,并且当选择一个项目时,主片段将被正确替换。

This is the onClickListener code: 这是onClickListener代码:

mDrawerListView.setOnItemClickListener(new AdapterView.OnItemClickListener() {
    @Override
    public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
        HeaderViewListAdapter headerView = (HeaderViewListAdapter) parent.getAdapter();
        AccountAdapter adapter = (AccountAdapter) headerView.getWrappedAdapter();
        Cursor cursor = adapter.getCursor();

        if(cursor != null && cursor.moveToPosition(position)){
            ((NavigationDrawerCallbacks) getActivity()).onNavigationDrawerItemSelected(cursor.getLong(cursor.getColumnIndex(ID_COLUMN)));
        }
    }
});

And in my activity, the onNavigationDrawerItemSelected method is like this: 在我的活动中,onNavigationDrawerItemSelected方法是这样的:

@Override
public void onNavigationDrawerItemSelected(long accountId) {
    // update the main content by replacing fragments
    FragmentManager fragmentManager = getSupportFragmentManager();
    fragmentManager.beginTransaction()
            .replace(R.id.mainFragment, AccountDetailFragment.newInstance(accountId))
            .commit();
}

As I said, this functions, but the navigation drawer remains open. 如我所说,此功能有效,但导航抽屉保持打开状态。 It's a hassle for the user to have to select an account from the listview and then have to close the drawer to see the main fragment, so how can I have it close automatically, so that when an item is selected the only visible element is the main fragment (and everything inside of it)? 用户必须从列表视图中选择一个帐户,然后必须关闭抽屉才能看到主要片段,这很麻烦,因此我如何自动关闭它,以便在选择项目时唯一可见的元素是主片段(以及其中的所有内容)?

使用Drawer View或Drawer's Gravity作为参数,在DrawerLayout对象上调用closeDrawer()

You need to call the closeDrawer inside the onItemClick, when the Drawer Layout is not null. 当Drawer Layout不为null时,需要在onItemClick内调用closeDrawer。

    if (mDrawerLayout != null) {
        mDrawerLayout.closeDrawer(mFragmentContainerView);
    }

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM