-
-
Save KaustubhPatange/fbdc6466819e04f4581cb959788d8c47 to your computer and use it in GitHub Desktop.
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
import android.app.Activity | |
import android.os.Build | |
import android.window.OnBackInvokedCallback | |
import androidx.activity.ComponentActivity | |
import androidx.activity.OnBackPressedCallback | |
import androidx.appcompat.app.AppCompatActivity | |
private typealias BackPressCallback = () -> Boolean | |
@Suppress("DEPRECATION") | |
open class BackPressCompatActivity : AppCompatActivity() { | |
private var listener: BackPressCallback? = null | |
/** | |
* A custom back press listener to support predictive back navigation | |
* introduced in Android 13. | |
* | |
* If return true, activity will finish otherwise no action taken. | |
*/ | |
fun setOnBackPressListener(block: BackPressCallback) { | |
listener = block | |
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.TIRAMISU) { | |
onBackInvokedDispatcher.registerOnBackInvokedCallback(1000, object: OnBackInvokedCallback { | |
override fun onBackInvoked() { | |
if (block()) { | |
onBackPressedDispatcher.onBackPressed() | |
} | |
} | |
}) | |
} | |
} | |
@Deprecated("Deprecated in Java") | |
final override fun onBackPressed() { | |
if (Build.VERSION.SDK_INT < Build.VERSION_CODES.TIRAMISU) { | |
if (listener?.invoke() == false) { | |
return | |
} | |
} | |
super.onBackPressed() | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment