Android up navigation in fragment pager adapter

404 Views Asked by At

I currently have different fragments that can open up same activities. Is there a way to implement the up navigation button such that when pressed, it goes back to the fragment that is came from Instead of it always being the starting fragment?

I've attached an image to better illustrate this.

enter image description here

The back press button works fine, just not sure on the up nav button.

Thanks.

2

There are 2 best solutions below

0
On

My solution might not be elegant but it is somehow effective.

First you should put in the intent the tag of the fragment that is starting the new activity. After you start the activity you call finish(); in the MainActivity.

In the new activity you override the onOptionsItemSelected method so it creates a new intent and starts the MainActivity. Of course, you will store again in the intent the tag of the fragment.

// Handles back button in ActionBar
@Override
public boolean onOptionsItemSelected(MenuItem item) {
    switch (item.getItemId()) {
        case android.R.id.home:
            Intent intent = new Intent(getApplicationContext(), MainActivity.class);
            intent.putExtra("lastFragment",value);
            startActivity(intent);
            finish();
            break;
    }
    return true;
}

Finally the MainActivity should check if the intent is null. If not, get the tag of the fragment and load it.

Intent intent = getIntent();
if(savedInstanceState!=null) {
    lastFrag = savedInstanceState.getString("lastFragment");
}

//Recreate the fragment

The final result is that the user will be prompted back to the fragment that called the new activity. Although I'm sure there are better ways to do this.

0
On

In your Fragments ...

@Override
public boolean onOptionsItemSelected(MenuItem item) {
    switch (item.getItemId()) {
        case android.R.id.home:
            if ( getActivity() != null ) {
                getActivity.onBackPressed();
            }
            break;
    }
    return true;
}

In your Activity ...

@Override
public void onBackPressed() {
    if ( viewPager != null && viewPager.getCurrentItem() != 0 ) {
        viewPager.setCurrentItem(0);
    }
}