Kurlicue Kurlicue - 5 months ago 15
Java Question

Toolbar hamburger interfering with back arrow button

I'm seting a drawer with an hamburger, when I open a fragment I want to remove the hamburger and replace it with an arrow that calls

onBackPressed()
.

What's happening is the hamburger gets replaced by the arrow, but the listener on the arrow doesn't get called. If I remove the
ActionBarDrawerToggle
completely it will work. How can I fix this?

Opening the new fragment:

Fragment_Subjects frag = new Fragment_Subjects();
fm.beginTransaction()
.replace(R.id.mainContainer, frag)
.addToBackStack(null)
.commit();
toggle.setDrawerIndicatorEnabled(false);
getSupportActionBar().setDisplayHomeAsUpEnabled(true);
getSupportActionBar().setHomeButtonEnabled(true);


Seting the drawer toggle:

drawer = (DrawerLayout) findViewById(R.id.drawer_layout);
toggle = new ActionBarDrawerToggle(this, drawer, mToolbar, R.string.navigation_drawer_open, R.string.navigation_drawer_close); //back arrow works when this line is removed
assert drawer != null;
drawer.setDrawerListener(toggle);
toggle.syncState();


Back arrow listener:

@Override
public boolean onOptionsItemSelected(MenuItem item) {
switch (item.getItemId()) {
case android.R.id.home:
onBackPressed();
return true;
}
return super.onOptionsItemSelected(item);
}


onBackPressed:

@Override
public void onBackPressed() {

if(drawer.isDrawerOpen(Gravity.START)){
drawer.closeDrawer(Gravity.START);
}else{
super.onBackPressed();
}
}

Answer

Try this:

 toolbar.setNavigationOnClickListener(new View.OnClickListener() {
        @Override
        public void onClick(View view) {
              onBackPressed();
        }
 });