MainActivity to fragment and back to MainActivity on pressing back button

前端 未结 4 1304
说谎
说谎 2020-12-20 00:26

I have a Mainactivity which contains a Layout which is parent of 4 sub layout. on clicking on sub layout i am going to a new fragment replacing main layout. But i cant go ba

4条回答
  •  温柔的废话
    2020-12-20 01:25

    Try Like this

        public boolean popFragment() {
        boolean isPop = false;
    
        Fragment currentFragment = getSupportFragmentManager()
                .findFragmentById(R.id.flContent);
    
            if (getSupportFragmentManager().getBackStackEntryCount() > 0) {
                isPop = true;
                getSupportFragmentManager().popBackStackImmediate();
            }
    
        return isPop;
    }
    
    @Override
    public void onBackPressed() {
        if (!popFragment()) {
            finish();
        }
    }
    
    public void replaceFragment(Fragment fragment, boolean addToBackStack) {
    
        FragmentTransaction transaction = getSupportFragmentManager()
                .beginTransaction();
    
        if (addToBackStack) {
            transaction.addToBackStack(null);
    
        } else {
            getSupportFragmentManager().popBackStack(null,
                    FragmentManager.POP_BACK_STACK_INCLUSIVE);
    
        }
        transaction.replace(R.id.fragment_container, fragment);
        transaction.commit();
        getSupportFragmentManager().executePendingTransactions();
    
    }
    

    add above method is in your parent Activity And Use like

     FragmentAboutUs fragmentAboutUs = new FragmentAboutUs();
     replaceFragment(fragmentAboutUs , true);
    

提交回复
热议问题