@@ -501,13 +501,49 @@ public static void openCommentAuthorIfPresent(@NonNull final FragmentActivity ac
501501
502502 public static void openCommentRepliesFragment (@ NonNull final FragmentActivity activity ,
503503 @ NonNull final CommentsInfoItem comment ) {
504+ closeCommentRepliesFragments (activity );
504505 defaultTransaction (activity .getSupportFragmentManager ())
505506 .replace (R .id .fragment_holder , new CommentRepliesFragment (comment ),
506507 CommentRepliesFragment .TAG )
507508 .addToBackStack (CommentRepliesFragment .TAG )
508509 .commit ();
509510 }
510511
512+ // This removes all of the top CommentRepliesFragment instances.
513+ // Ideally there should only be one since we remove existing before opening a new one.
514+ public static void closeCommentRepliesFragments (@ NonNull final FragmentActivity activity ) {
515+ final FragmentManager fm = activity .getSupportFragmentManager ();
516+
517+ // Remove all existing fragment instances tagged as CommentRepliesFragment
518+ final FragmentTransaction tx = defaultTransaction (fm );
519+ boolean removed = false ;
520+ for (final Fragment fragment : fm .getFragments ()) {
521+ if (fragment != null && CommentRepliesFragment .TAG .equals (fragment .getTag ())) {
522+ tx .remove (fragment );
523+ removed = true ;
524+ }
525+ }
526+ if (removed ) {
527+ tx .commit ();
528+ }
529+
530+ // Only pop back stack entries named CommentRepliesFragment.TAG if they are at the top.
531+ while (true ) {
532+ final int count = fm .getBackStackEntryCount ();
533+ if (count == 0 ) {
534+ break ;
535+ }
536+ final FragmentManager .BackStackEntry topEntry = fm .getBackStackEntryAt (count - 1 );
537+ final String topName = topEntry .getName ();
538+ if (CommentRepliesFragment .TAG .equals (topName )) {
539+ // Safe to pop the topmost matching entry (it won't remove other unrelated entries)
540+ fm .popBackStackImmediate (topName , FragmentManager .POP_BACK_STACK_INCLUSIVE );
541+ } else {
542+ break ;
543+ }
544+ }
545+ }
546+
511547 public static void openPlaylistFragment (final FragmentManager fragmentManager ,
512548 final int serviceId , final String url ,
513549 @ NonNull final String name ) {
0 commit comments