简体   繁体   中英

Actionbar Up Button Listener

I have only one activity in my application which contains navigation view to navigate through 3 fragments.

When I navigate to a fragment I get the hamburger menu icon changed to the up button in the onNavigationItemSelected method like this:

actionBarDrawerToggle.setDrawerIndicatorEnabled(false);
getSupportActionBar().setDisplayHomeAsUpEnabled(true);

The up button appears well but has no effect yet.

I wanna navigate to the previous fragment in the stack when the button is clicked but I can't get to add a listener to that button.

I've tried using:

@Override
public boolean onOptionsItemSelected(MenuItem item) {
    int id = item.getItemId();
    if (id == android.R.id.home) {
        onBackPressed();
        return true;
    }

    return super.onOptionsItemSelected(item);
}

but this is never called. I think it's not called because I have no parent activity in the manifest.

Thanks in advance.

You should not call onBackPressed, you should use fragment transaction method to to transact between fragments like I replaced my current fragment with previous fragment using replace method. container is the layout containing the fragments.

  FragmentTransaction transaction = getSupportFragmentManager().beginTransaction();
 transaction.replace(R.id.fragment_container, newFragment); 
     transaction.commit();  

I hope, it give you some direction.

 if (id == android.R.id.home) {
    //put the code like above here.
    return true;
}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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