再次按下Drawertoggle后关闭抽屉

时间:2017-12-27 18:18:47

标签: java android navigation

我想在再次按下切换按钮后关闭Navigationdrawer。现在,如果切换按钮,它只会打开抽屉。我可以在选择一个项目后关闭抽屉。

是否可以实施我的方法,关闭抽屉?

这是我的方法:

@Override
    public boolean onCreateOptionsMenu(Menu menu) {
        return true;
    }
    @Override
    public boolean onOptionsItemSelected(MenuItem item) {
        switch (item.getItemId()) {
            case android.R.id.home:
                mDrawerLayout.openDrawer(GravityCompat.START);   //THIS OPENS THE DRAWER
                return true;
        }
        return super.onOptionsItemSelected(item);
    }

    private void setupDrawerContent(NavigationView navigationView) {
        navigationView.setNavigationItemSelectedListener(
                new NavigationView.OnNavigationItemSelectedListener() {
                    @Override
                    public boolean onNavigationItemSelected(MenuItem menuItem) {
                        menuItem.setChecked(true);
                        mDrawerLayout.closeDrawers();        //THIS CLOSES THE DRAWER; AFTER A ITEM IS SELECTED
                        return true;
                    }
                });
    }

1 个答案:

答案 0 :(得分:1)

我很容易猜到。通过引入新的public boolean isDrawerOpen成员

来跟踪它是否开放

Lemme尝试这样的事情

@Override
public boolean onOptionsItemSelected(MenuItem item) {
    switch (item.getItemId()) {
        case android.R.id.home:
            if (!isDrawerOpen) {
                mDrawerLayout.openDrawer(GravityCompat.START);
                isDrawerOpen = true;
            } else {
                mDrawerLayout.closeDrawers();
                isDrawerOpen = false;
            }
            return true;
    }
    return super.onOptionsItemSelected(item);
}

private void setupDrawerContent(NavigationView navigationView) {
    navigationView.setNavigationItemSelectedListener(
            new NavigationView.OnNavigationItemSelectedListener() {
                @Override
                public boolean onNavigationItemSelected(MenuItem menuItem) {
                    menuItem.setChecked(true);
                    mDrawerLayout.closeDrawers();        //THIS CLOSES THE DRAWER; AFTER A ITEM IS SELECTED
                    isDrawerOpen = false;
                    return true;
                }
            });
}