|
| 1 | +// Public API |
| 2 | +@file:Suppress("unused") |
| 3 | + |
| 4 | +package com.redmadrobot.extensions.fragment |
| 5 | + |
| 6 | +import androidx.activity.OnBackPressedCallback |
| 7 | +import androidx.annotation.MainThread |
| 8 | +import androidx.fragment.app.Fragment |
| 9 | + |
| 10 | +/** |
| 11 | + * Create and add a new [OnBackPressedCallback] tied to [Fragment.getViewLifecycleOwner] |
| 12 | + * that calls [onBackPressed] in [OnBackPressedCallback.handleOnBackPressed]. |
| 13 | + * |
| 14 | + * Callback should be added in [Fragment.onAttach] or later. Callbacks are tied to [Fragment.getViewLifecycleOwner] so |
| 15 | + * it will only be added when the fragment view's Lifecycle is [androidx.lifecycle.Lifecycle.State.STARTED]. |
| 16 | + * ``` |
| 17 | + * class FormEntryFragment : Fragment() { |
| 18 | + * override fun onAttach(context: Context) { |
| 19 | + * super.onAttach(context) |
| 20 | + * addOnBackPressedCallback { |
| 21 | + * showAreYouSureDialog() |
| 22 | + * } |
| 23 | + * } |
| 24 | + * } |
| 25 | + * ``` |
| 26 | + * @param enabled Callback state. By default is `true`. |
| 27 | + * @return Created callback. You can manage it using [OnBackPressedCallback.setEnabled] and |
| 28 | + * [OnBackPressedCallback.remove]. |
| 29 | + * @see OnBackPressedCallback |
| 30 | + * @see androidx.activity.OnBackPressedDispatcher |
| 31 | + */ |
| 32 | +@MainThread |
| 33 | +public inline fun Fragment.addOnBackPressedCallback( |
| 34 | + enabled: Boolean = true, |
| 35 | + crossinline onBackPressed: OnBackPressedCallback.() -> Unit |
| 36 | +): OnBackPressedCallback { |
| 37 | + return object : OnBackPressedCallback(enabled) { |
| 38 | + override fun handleOnBackPressed() = onBackPressed() |
| 39 | + }.also { requireActivity().onBackPressedDispatcher.addCallback(viewLifecycleOwner, it) } |
| 40 | +} |
0 commit comments