@@ -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+ /**
513+ * Closes all open {@link CommentRepliesFragment}s in {@code activity},
514+ * including those that are not at the top of the back stack.
515+ * This is needed to prevent multiple open CommentRepliesFragments
516+ * Ideally there should only be one since we remove existing before opening a new one.
517+ * @param activity the activity in which to close the CommentRepliesFragments
518+ */
519+ public static void closeCommentRepliesFragments (@ NonNull final FragmentActivity activity ) {
520+ final FragmentManager fm = activity .getSupportFragmentManager ();
521+
522+ // Remove all existing fragment instances tagged as CommentRepliesFragment
523+ final FragmentTransaction tx = defaultTransaction (fm );
524+ boolean removed = false ;
525+ for (final Fragment fragment : fm .getFragments ()) {
526+ if (fragment != null && CommentRepliesFragment .TAG .equals (fragment .getTag ())) {
527+ tx .remove (fragment );
528+ removed = true ;
529+ }
530+ }
531+ if (removed ) {
532+ tx .commit ();
533+ }
534+
535+ // Only pop back stack entries named CommentRepliesFragment.TAG if they are at the top.
536+ while (fm .getBackStackEntryCount () > 0
537+ && CommentRepliesFragment .TAG .equals (
538+ fm .getBackStackEntryAt (fm .getBackStackEntryCount () - 1 ).getName ()
539+ )
540+ ) {
541+ fm .popBackStackImmediate (CommentRepliesFragment .TAG ,
542+ FragmentManager .POP_BACK_STACK_INCLUSIVE );
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