proper backstack navigation on pressing Up button

114 Views Asked by At

I implemented backstack navigation on Back button in MainActivity (which have many fragments) using onBackPressed(). I want to implement same backstack navigation on Up button press. Problem is I only want Up button in one fragment but the Up button appears on every fragment when I press Up button on desired fragment. Even setDisplayHomeAsEnabled(false) is not working. How to have Up button in one fragment only?

Desired Fragment:

 @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
      ((AppCompatActivity)getActivity()).getSupportActionBar().setDisplayHomeAsUpEnabled(true);
      
   }   
Main Activity

public class HomePage extends AppCompatActivity {

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.homepage);


        if (findViewById(R.id.fragment_place) != null) {

            if (savedInstanceState != null) {
                return;
            }
            HomeFrag firstFragment = new HomeFrag();
            getSupportFragmentManager().beginTransaction().add(R.id.fragment_place, firstFragment).commit();
        }

    }

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


    public void selectFrag(View view) {
        Fragment fr = null;

        if (view == findViewById(R.id.home_btn)) {
            fr = new HomeFrag();

        } else if (view == findViewById(R.id.search_btn)) {
            fr = new SearchFrag();


        } else if (view == findViewById(R.id.log_btn)) {
            fr = new LogFrag();

        } else if (view == findViewById(R.id.events_btn)) {
            fr = new EventFrag();

        } else if (view == findViewById(R.id.profile_btn)) {
            fr = new ProfileFrag();

        }

        FragmentManager fm = getSupportFragmentManager();
        FragmentTransaction fragmentTransaction = fm.beginTransaction();
        fragmentTransaction.replace(R.id.fragment_place, fr).addToBackStack(null);
        fragmentTransaction.commit();

    }

    @Override
    public void onBackPressed() {
        if (getFragmentManager().getBackStackEntryCount() > 0)
            getFragmentManager().popBackStack();
        else
            super.onBackPressed();
    }
}

1

There are 1 best solutions below

1
On

I created a sample application on GitHub to solve such backstack problem.

Download Fragment Back Stack application