Skip to content
This repository has been archived by the owner on Mar 16, 2021. It is now read-only.

Commit

Permalink
Merge pull request #205 from grandcentrix/bugfix/androidx_fragment_1_…
Browse files Browse the repository at this point in the history
…2_0_isinbackstack

workaround for AndroidX Fragment 1.2.0 isInBackStack bug
  • Loading branch information
jannisveerkamp authored Jan 28, 2020
2 parents 887bcf5 + aaea0a2 commit 2bf7c1b
Showing 1 changed file with 28 additions and 0 deletions.
Original file line number Diff line number Diff line change
Expand Up @@ -4,6 +4,7 @@
import androidx.fragment.app.FragmentManager;
import java.io.PrintWriter;
import java.io.StringWriter;
import java.lang.reflect.Field;

/**
* Reads package private information about the {@link FragmentManager} backstack
Expand All @@ -23,9 +24,36 @@ public class BackstackReader {
* Hacky workaround because Fragment#isInBackStack is inaccessible with AndroidX
*/
public static boolean isInBackStack(final Fragment fragment) {
return isInBackStackAndroidX120(fragment);
}

/**
* Implementation which worked with AndroidX Fragment 1.1.0 and should be working again from 1.2.1:
* https://issuetracker.google.com/issues/148189412
*/
private static boolean isInBackStackAndroidXOld(final Fragment fragment) {
final StringWriter writer = new StringWriter();
fragment.dump("", null, new PrintWriter(writer), null);
final String dump = writer.toString();
return !dump.contains("mBackStackNesting=0");
}

/**
* Temporary hack for the hack ;) because in AndroidX Fragment 1.2.0 the original `fragment.dump` hack stopped working:
* https://github.com/sockeqwe/mosby/issues/318#issuecomment-577660091
*
* Uses reflection, so should be removed once AndroidX Fragment 1.2.1 is released.
*/
private static boolean isInBackStackAndroidX120(final Fragment fragment) {
try {
final Field backStackNestingField = Fragment.class.getDeclaredField("mBackStackNesting");
backStackNestingField.setAccessible(true);
final int backStackNesting = backStackNestingField.getInt(fragment);
return backStackNesting > 0;
} catch (NoSuchFieldException e) {
throw new RuntimeException(e);
} catch (IllegalAccessException e) {
throw new RuntimeException(e);
}
}
}

0 comments on commit 2bf7c1b

Please sign in to comment.