To implement Predictive Back feature in an app, that uses Fragments and Navigation Component, there are 2 options:
Option A: Use Transition API.
Just set animator animations directly into nav_graph actions:
<!-- nav_graph.xml -->
<action
android:id="..."
app:destination="..."
app:exitAnim="@animator/nav_default_exit_anim" />
Or assign Transition instances (like Fade or Slide) into Fragment transition properties (enterTransition, exitTransition, etc):
// Fragment's OnViewCreated
returnTransition = Slide(Gravity.END)
Option B: Use OnBackPressedCallback.
It provides predictive back progress methods, where you can animate manually (code sample).
What if I want to implement predictive back for fragments, but play different transition animations depending on where back gesture started (at least side of the screen)?
Option B provides us with handleOnBackStarted method with BackEventCompat parameter, which can give us side of the gesture with getSwipeEdge method, and handleOnBackProgressed method to animate. But there is a limitation (mentioned in the docs): "users cannot see previous fragment when swiping back" - i.e. no seeking. So there is almost no point to use this option for implementing predictive back - when progressing with animation user will see blank screen instead of previous fragment.
Option A works good, seeking supported, but there is no way of detecting the side and starting coordinates of the gesture with this approach.
Combining options also doesn't work, because adding OnBackPressedCallback handles control over seeking from Transition API to callback, and defined Transition animation just plays after handleOnBackPressed.
Some other options I thought about:
create custom
FragmentNavigatorto useFragmentTransaction'saddandhideand then to be able to use previous fragment view for seeking insideOnBackPressedCallback. Looks like overhead to keep all previous fragments in memorysomehow pass current fragment view to the next fragment and use it inside
OnBackPressedCallbackfor seeking. Also may be memory inefficientmanually call previous fragment
OnCreateViewto get the view for seeking insideOnBackPressedCallback. Double view creation, view inconsistencies, memory issues, etc.detect back gesture using invisible views at the sides of the screen - detection will happen after predictive back started.
So, am I missing something or is this really impossible to do with fragments?