Skip to content

Commit 3a48f4a

Browse files
committed
fragment-ktx: Add Fragment.addOnBackPressedCallback
1 parent f68bd5d commit 3a48f4a

File tree

3 files changed

+47
-1
lines changed

3 files changed

+47
-1
lines changed

fragment-ktx/README.md

+5-1
Original file line numberDiff line numberDiff line change
@@ -31,7 +31,11 @@ dependencies {
3131

3232
## Extensions
3333

34-
> Extensions will be listed here
34+
Extensions for `Fragment`:
35+
36+
- `Fragment.addOnBackPressedCallback(enabled: Boolean = true, onBackPressed: OnBackPressedCallback.() -> Unit)`
37+
38+
Create and add a new `OnBackPressedCallback` tied to `Fragment.viewLifecycleOwner` that calls `onBackPressed` in `OnBackPressedCallback.handleOnBackPressed`.
3539

3640
## Contributing
3741

fragment-ktx/build.gradle.kts

+2
Original file line numberDiff line numberDiff line change
@@ -12,4 +12,6 @@ description = "A set of extensions in addition to androidx fragment-ktx"
1212
dependencies {
1313
api(jetbrains.kotlin.stdlib)
1414
api(androidx.fragment.ktx)
15+
api(androidx.activity)
16+
api(androidx.annotation)
1517
}
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,40 @@
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

Comments
 (0)