再次按下Drawertoggle后关闭抽屉

问题描述 投票:-1回答:1

我想再次按下切换按钮后关闭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;
                    }
                });
    }
java android navigation
1个回答
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;
                }
            });
}
© www.soinside.com 2019 - 2024. All rights reserved.