How to go back to first Android Fragment after replace

后端 未结 1 1170
佛祖请我去吃肉
佛祖请我去吃肉 2020-12-22 07:37

I\'m trying to get back to the first fragment after replacing it, but supportFragmentManager.popBackStackImmediate() do not work...

override fun onCreate(sav         


        
相关标签:
1条回答
  • 2020-12-22 08:20

    At starting i use popbackstack method but in this it iterate loop every time when back button is pressed. So i change my concept instead of popbackstack i maintain constant variable. and using this i manage my fragment. For that Follow Below Steps.

    Step 1: make atleast two Global Variable.

        public static String currentTAG="HomeFragment";
        public static String AboutUsFragment="AboutUsFragment";
        public static String HelpfulTipsFragment="HelpfulTipsFragment";
    

    Step 2: Change CurrentTag value when Fragment Open.

    In Home Fragment in currentTAG=HomeFragment similarly for aboutUsFragment set CurrentTAG=AboutUsFragment;

    Step 3: Then After in Your main Activity Write down Below Code in Onbackpress method.

    if (Const.currentTAG.equals(Const.HomeFragment)) {
                ExitApp();
            }else{
             getSupportFragmentManager().beginTransaction().replace(R.id.maincontainer, new HomeFragment()).addToBackStack(null).commit();
            }
    
    
          private void ExitApp() {
        final AlertDialog.Builder builder = new AlertDialog.Builder(context);
    
        builder.setTitle(R.string.app_name);
        builder.setMessage(R.string.ask_before_close);
        builder.setIcon(R.mipmap.ic_launcher);
        //final AlertDialog dialog = builder.create();
        builder.setPositiveButton("YES", new DialogInterface.OnClickListener() {
            @Override
            public void onClick(DialogInterface dialogInterface, int i) {
    
                finish();
    
            }
        });
        builder.setNegativeButton("NO", new DialogInterface.OnClickListener() {
            @Override
            public void onClick(DialogInterface dialogInterface, int i) {
    
            }
        });
        builder.show();
    }
    

    Similarly You Can Manage Multiple Fragment Without Iterating loop and popbackstack.

    NOTE: When You Load Fragment Use Replace instead of add like below Code

     getSupportFragmentManager().beginTransaction().replace(R.id.maincontainer, new AboutAppFragment()).addToBackStack(null).commit();
    
    0 讨论(0)
提交回复
热议问题