简体   繁体   English

onBackPressed() 已弃用,有什么替代方案?

[英]onBackPressed() deprecated, What is the alternative?

I have upgraded targetSdkVersion and compileSdkVersion to 33 .我已经将targetSdkVersioncompileSdkVersion升级到33

Now getting warning onBackPressed is deprecated.现在不推荐使用onBackPressed警告。

It is suggested to use use OnBackInvokedCallback or androidx.activity.OnBackPressedCallback to handle back navigation instead.建议改用OnBackInvokedCallbackandroidx.activity.OnBackPressedCallback来处理返回导航。 Anyone can help me to use the updated method.任何人都可以帮助我使用更新的方法。

Example:例子:

onBackPressed已弃用

Use Case: I use if (isTaskRoot) {} inside onBackPressed(){} method to check activity is last on the activity-stack.用例:我在onBackPressed(){}方法中使用if (isTaskRoot) {}来检查活动是否位于活动堆栈的最后。

override fun onBackPressed() {
    if (isTaskRoot) { // Check this activity is last on the activity-stack.(Check Whether This activity opened from Push-Notification)
        startActivity(Intent(mContext, Dashboard::class.java))
        finish()
    } else {
        finishWithResultOK()
    }
}

Replace onBackPressed() with below code.将 onBackPressed() 替换为以下代码。

onBackPressedDispatcher.onBackPressed()

With a combination of top answers.结合最佳答案。 Here is a solution:这是一个解决方案:

1. When you need to press the back button, copy this: 1.当你需要按返回键的时候,复制这个:

Note: it will automatically destroy your activity.注意:它会自动销毁你的活动。

button.setOnClickListener {
    onBackPressedDispatcher.onBackPressed()
}

2. When you need to handle the back button pressed, copy this: 2.当你需要处理按下的后退按钮时,复制这个:

onBackPressedDispatcher.addCallback(this, object: OnBackPressedCallback(true) {
    override fun handleOnBackPressed() {
        // Whatever you want
        // when back pressed
        println("Back button pressed")
        finish()
    }
})

In Kotlin , this way is workingKotlin中,这种方式有效

1- Remove onBackPressed() 1- 删除onBackPressed()

2- below onCreate(savedInstanceState: Bundle?) add these lines: 2- 在onCreate(savedInstanceState: Bundle?)下面添加这些行:

 if (Build.VERSION.SDK_INT >= 33) {
        onBackInvokedDispatcher.registerOnBackInvokedCallback(
            OnBackInvokedDispatcher.PRIORITY_DEFAULT
        ) {
           
            exitOnBackPressed()
        }
    } else {
        onBackPressedDispatcher.addCallback(
            this,
            object : OnBackPressedCallback(true) {
                override fun handleOnBackPressed() {
                  
                    Log.i("TAG", "handleOnBackPressed: Exit")
                    exitOnBackPressed()
                }
            })
    }

3- Define a new function for handling 3-定义一个新的处理函数

fun exitOnBackPressed() {
}

According your API level register:根据您的 API 级别寄存器:

This requires to at least use appcompat:1.6.0-alpha03 ;这需要至少使用appcompat:1.6.0-alpha03 the current is 1.6.0-alpha04 :当前是1.6.0-alpha04

 implementation 'androidx.appcompat:appcompat:1.6.0-alpha04'
if (BuildCompat.isAtLeastT()) {
    onBackInvokedDispatcher.registerOnBackInvokedCallback(
        OnBackInvokedDispatcher.PRIORITY_DEFAULT
    ) {
        // Back is pressed... Finishing the activity
        finish()
    }
} else {
    onBackPressedDispatcher.addCallback(
        this, // lifecycle owner
        object : OnBackPressedCallback(true) {
            override fun handleOnBackPressed() {
                // Back is pressed... Finishing the activity
                finish()
            }
        })
}

UPDATE:更新:

Thanks to @ianhanniballake comment;感谢@ianhanniballake 评论; you can just use OnBackPressedDispatcher even in API level 33+即使在 API 级别 33+ 中,您也可以使用OnBackPressedDispatcher

The OnBackPressedDispatcher is already going to be using the Android T specific API internally when using Activity 1.6+, OnBackPressedDispatcher 在使用 Activity 1.6+ 时已经在内部使用 Android T 特定的 API,

So, you can just do:所以,你可以这样做:

onBackPressedDispatcher.addCallback(
    this, // lifecycle owner
    object : OnBackPressedCallback(true) {
        override fun handleOnBackPressed() {
            // Back is pressed... Finishing the activity
            finish()
        }
    })

Note that you shouldn't override the onBackPressed() as that will make the onBackPressedDispatcher callback not to fire;请注意,您不应覆盖onBackPressed() ,因为这会使onBackPressedDispatcher回调不触发; check this answer for clarifying that.检查此答案以澄清这一点。

Simply replace只需更换

override fun onBackPressed() {
      super.onBackPressed() //Replace this is deprecated line
}

with

override fun onBackPressed() {
      onBackPressedDispatcher.onBackPressed() //with this line
}

You can use the OnBackInvokedCallback您可以使用 OnBackInvokedCallback

OnBackInvokedCallback as described in the documentation and follow this guide here to update your code如文档中所述,并在此处按照本指南更新您的代码

Here is the extension function to implement OnBackPressedCallback in activity.这是在活动中实现 OnBackPressedCallback 的扩展函数。

fun AppCompatActivity.addOnBackPressedDispatcher(onBackPressed: () -> Unit = { finish() }) {
    onBackPressedDispatcher.addCallback(
        this,
        object : OnBackPressedCallback(true) {
            override fun handleOnBackPressed() {
                onBackPressed.invoke()
            }
        }
    )
}

Usage:用法:

addOnBackPressedDispatcher {
    //doSomething()
}

You could use the onBackPressedDispatcher您可以使用onBackPressedDispatcher

onBackPressedDispatcher.addCallback(this, object : OnBackPressedCallback(true) {
    override fun handleOnBackPressed() {
        finish() //finshes the activity when back pressed.simillar to the super.onbackpressed
    }
})

in here "this" means the lifeCycleOwner这里的“this”是指 lifeCycleOwner

Use like below,像下面这样使用,

 override fun onClick(v: View?) { when (v?.id) { R.id.iv_back -> onBackPressedMethod() } }

and now create that method for handling back event现在创建该方法来处理返回事件

 private fun onBackPressedMethod(){ if (Build.VERSION.SDK_INT >= 33) { onBackInvokedDispatcher.registerOnBackInvokedCallback( OnBackInvokedDispatcher.PRIORITY_DEFAULT) { // back button pressed... finishing the activity finish() } } else { onBackPressedDispatcher.addCallback( this, object: OnBackPressedCallback(true) { override fun handleOnBackPressed() { // back button pressed... finishing the activity finish() } }) } }

That's it!而已!

Bonus: To close DrawerLayout when onBackPressed use like below (according to this I/O talk ),奖励:在 onBackPressed 使用时关闭 DrawerLayout,如下所示(根据这个 I/O talk ),

val callback = onBackPressedDispatcher.addCallback(this, false) {
    binding.drawerLayout.closeDrawer(GravityCompat.START)
}
            
binding.drawerLayout.addDrawerListener(object : DrawerListener {  
        
    override fun onDrawerOpened(drawerView: View) {
        callback.isEnabled = true
    }
        
    override fun onDrawerClosed(drawerView: View) {
        callback.isEnabled = false
    }

    override fun onDrawerSlide(drawerView: View, slideOffset: Float) = Unit    
    override fun onDrawerStateChanged(newState: Int) = Unit
})

use onBackPressedDispatcher.onBackPressed() instead of super.onBackPressed()使用 onBackPressedDispatcher.onBackPressed() 而不是 super.onBackPressed()

override the onDismiss() function for BottomSheets.覆盖 BottomSheets 的 onDismiss() function。

override fun onDismiss(dialog: DialogInterface) {
   super.onDismiss(dialog)
   //TODO your logic.
   }

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

相关问题 getSerializableExtra 已弃用,有什么替代方案? - getSerializableExtra deprecated, What is the alternative? getParcelableArrayListExtra 已弃用 有什么替代方案? - getParcelableArrayListExtra deprecated what is the alternative? isMinifyEnabled()已弃用。 有什么选择? - isMinifyEnabled() is deprecated. What is the alternative? OnActivityResult 方法已弃用,替代方法是什么? - OnActivityResult method is deprecated, what is the alternative? 是否有服务的onBackPressed()替代方案? - Is there an onBackPressed() alternative for a service? HttpEntity现在在Android上被弃用了,还有什么选择? - HttpEntity is deprecated on Android now, what's the alternative? Android中不推荐使用的AbsoluteLayout替代品是什么? - What's alternative to deprecated AbsoluteLayout in Android? 已弃用的 Canvas.getMatrix() 的替代方案是什么? - What is the alternative for deprecated Canvas.getMatrix()? Android:StatusLine 现在已弃用,有什么替代方案? - Android: StatusLine now deprecated, what is the alternative? android中已弃用的cachemanager类的替代方法是什么? - what is the alternative for the deprecated cachemanager class in android
 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM