Skip to content

Instantly share code, notes, and snippets.

@KaustubhPatange
Last active February 12, 2023 07:26
Show Gist options
  • Save KaustubhPatange/fbdc6466819e04f4581cb959788d8c47 to your computer and use it in GitHub Desktop.
Save KaustubhPatange/fbdc6466819e04f4581cb959788d8c47 to your computer and use it in GitHub Desktop.
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