How to resume Fragment from BackStack if exists

前端 未结 6 1080
野的像风
野的像风 2020-11-22 13:29

I am learning how to use fragments. I have three instances of Fragment that are initialized at the top of the class. I am adding the fragment to an activity lik

6条回答
  •  忘掉有多难
    2020-11-22 14:09

    I think this method my solve your problem:

    public static void attachFragment ( int fragmentHolderLayoutId, Fragment fragment, Context context, String tag ) {
    
    
        FragmentManager manager = ( (AppCompatActivity) context ).getSupportFragmentManager ();
        FragmentTransaction ft = manager.beginTransaction ();
    
        if (manager.findFragmentByTag ( tag ) == null) { // No fragment in backStack with same tag..
            ft.add ( fragmentHolderLayoutId, fragment, tag );
            ft.addToBackStack ( tag );
            ft.commit ();
        }
        else {
            ft.show ( manager.findFragmentByTag ( tag ) ).commit ();
        }
    }
    

    which was originally posted in This Question

提交回复
热议问题