I recently had to do this and decided that a switch statement was the best way to go. Essentially you keep track of what fragment you're in now, and then switch to another one based on whatever criteria you set. For me, it was navigating back from one fragment to another.
@Override
public boolean onOptionsItemSelected(MenuItem item) {
switch (item.getItemId()) {
...
case android.R.id.home:
switch(currentFragment){
case FRAGMENT1:
FragmentTransaction transaction = fragmentManager.beginTransaction();
transaction
.replace(R.id.fragment_container, fragment2);
transaction.commit();
currentFragment = FRAGMENT_2;
return true;
default:
FragmentTransaction transaction = fragmentManager.beginTransaction();
transaction
.replace(R.id.fragment_container, fragment1);
transaction.commit();
currentFragment = FRAGMENT_1;
return true;
}
}
I'm assuming you mean you'd want to end the current activity you're in and display a fragment? In this case there'd probably be a parent FragmentActivity (to host the fragment), so you'd just end the current Activity and start another in the typical way. Once again:
@Override
public boolean onOptionsItemSelected(MenuItem item) {
switch (item.getItemId()) {
...
case android.R.id.home:
Intent intent = new Intent(this, NewFragmentActivity.class);
intent.putExtra(...); // so you can pass what activity you're coming from, if needed
startActivity(intent);
this.finish();
Keep in mind this is just a button and you're essentially assigning the onClick() action through case android.R.id.home: