ActionBarDrawerToggle with AppCompatActivity and Toolbar Back button with Fragments

后端 未结 2 1221
长情又很酷
长情又很酷 2021-01-23 14:52

I am using the ActionBarDrawerToggle with NavigationView. My content is displayed using fragments.

I am following this stackoverflow question to get the back button pres

相关标签:
2条回答
  • 2021-01-23 15:27

    If you want the onOptionsItemSelected() method to fire upon clicking the toggle, remove the toolbar argument from the ActionBarDrawerToggle constructor call.

    mDrawerToggle = new ActionBarDrawerToggle(this, mDrawerLayout,
        R.string.openDrawerContentDescRes, R.string.closeDrawerContentDescRes);
    

    Otherwise, the toggle handles opening and closing the drawer internally, and the call to ActionBarDrawerToggle#onOptionsItemSelected() isn't necessary.

    If you want to handle clicking the home Button differently depending on the current state, you'll also want to remove the if block that returns at the top of the onOptionsItemSelected() method.

    And, you should call setDisplayHomeAsUpEnabled(true) just once in onCreate(). You don't need to keep switching that on and off. Enabling and disabling the drawer indicator will take care of that.

    0 讨论(0)
  • 2021-01-23 15:28

    Remove this line

     if (mDrawerToggle.onOptionsItemSelected(item)) {
            return true;
        }
    

    from onOptionsItemSelected() so it will look like this

    @Override
    public boolean onOptionsItemSelected(MenuItem item) {
    
    switch (item.getItemId()) {
        case android.R.id.home:
            // doesn't reach here ever.
            return true;
        case R.id.action_x:
            // do something
            return true;
        case R.id.action_y:
            // do something
            return true;
        default:
            return super.onOptionsItemSelected(item);
    }
    }
    
    0 讨论(0)
提交回复
热议问题