Android onBackPressed()已被弃用

ComponentActivity.onBackPressed()现在已被弃用,取而代之的是用于回处理的API。

现在应该利用OnBackPressedDispatcher,而不是重写此方法。

class FormEntryFragment : Fragment() {
  override fun onAttach(context: Context) {
    super.onAttach(context)
    val callback = object : OnBackPressedCallback(
      true // default to enabled
    ) {
      override fun handleOnBackPressed() {
        showAreYouSureDialog()
      }
    }
    requireActivity().onBackPressedDispatcher.addCallback(
      this, // LifecycleOwner
      callback
    )
  }
}

或者用新的预测性后退回调

  PredictiveBackHandler { progress: Flow ->
    // code for gesture back started
    try {
      progress.collect { backEvent ->
      // code for progress
    }
    // code for completion
    } catch (e: CancellationException) {
      // code for cancellation
    }
  }

你可能感兴趣的:(android)