onbackpressed()已弃用。什么是选择?
我已经升级了 targetsdkversion
和 compilesdkversion
33
。
我现在得到一个警告,告诉我 onbackpressed 已弃用。
我看到建议使用 android.window.onbackinvokedcallback ://developer.android.com/reference/androidx/activity/onbackpressedcallback“ rel =“ noreferrer”> androidx.activity.onbackpressevervity.onbackpressedcallback 代替处理返回导航。谁能帮助我使用更新的方法?
示例
用例
i使用 if(istaskroot){}
onbackpressed()检查活动是否是活动堆栈上的最后一个方法。
override fun onBackPressed() {
if (isTaskRoot) { // Check whether this activity is last on the activity stack. (Check whether this activity opened from a Push Notification.)
startActivity(Intent(mContext, Dashboard::class.java))
finish()
} else {
finishWithResultOK()
}
}
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(26)
如果您使用的是Java,那么这是我正在这样做的方法。
然后,如果您想强制呼叫onbacked,则可以使用以下方式进行以下操作:
If you're using Java then here's a way I'm doing it.
Then if you want to force call onBackPressed you can do it using:
如果您喜欢“后面”按钮处理,则需要在活动的OnCreate()方法中进行此部分。不要忘记实际完成handleonbackpressed()中的活动。
如果您的活动中有箭头,则涉及用于AppCompatactivity的方法OnSupportNavigateUp()。
因此,您还需要处理此问题。这样做。
If you like the back button handled you need this part in your onCreate() method of your activity. Don't forget to actually finish the activity in the handleOnBackPressed().
If you have a up arrow inside your activity, this involves the method onSupportNavigateUp() for AppCompatActivity.
So you also need to handle this. Do it this way.
奖励:当onbackpressed使用如下(根据此i/o谈话),
Bonus: To close DrawerLayout when onBackPressed use like below (according to this I/O talk),
这是在活动中实现OnbackPressedCallback的扩展功能。
用法:
Here is the extension function to implement OnBackPressedCallback in activity.
Usage:
我通过简单地将扩展名添加到
appCompatactivity
:我可以通过两种方式调用“ onbackbuttonpressed”来使用它来解决此问题,以两种方式
1-实现后面按下以完成活动
2-句柄后面的partive 2-句柄后面按下:
I solved this by simply adding an extension to
AppCompatActivity
:So I can use it by calling "onBackButtonPressed" in two ways
1- Implement back pressed to finish activity
2- Handle back pressed clicks:
首先,我们必须添加一个回调对象,因为,
onbackpresseddispatcher.onbackpresse()
触发了呼叫当前添加的回调,以相反的顺序添加。因此,添加回调后,我们应该调用方法
onbackpressed()
代码(在Kotlin中)如下:
first,we have to add a callback object because,
onBackPressedDispatcher.onBackPressed()
triggers a call to the currently added callbacks in reverse order in which they were added.So after adding the callback only we should call the method
onBackPressed()
The code (in kotlin) is as follows:
基于上面的所有答案( this 和 this )我创建了这些简单的扩展名,这些扩展使您可以使用Onbackpressed函数的相同体验。我们使用
onbackpresseddispatcher
来处理返回按钮。首先,将
appCompat:1.6.1
(或本库的任何较新版本)添加到您的gradle配置中。然后,基于目标视图,您可以使用以下扩展名之一:
活动:
片段:
对话:
用法:
将此功能添加到您的
increate()
方法:如果您想完全覆盖返回按钮,则可以返回
true
,并且如果让系统处理返回按钮,则需要在回调结束时返回false
。最后但并非最不重要的一点是,如果您想手动执行活动或 fragment 中的后退按钮,只需致电:
Based on all answers above (this, and this) I created these simple extensions which give you the same experience of using the onBackPressed function. we use
onBackPressedDispatcher
for handling the back button.First, add
appcompat:1.6.1
(or any newer version of this library) to your gradle config.Then based on your target view you can use one of these extensions:
Activity:
Fragment:
Dialog:
Usage:
Add this function to your
OnCreate()
method:If you want to fully override the back button you can return
true
and in case of letting the system handle the back button, you need to returnfalse
at the end of the callback.Last but not least, if you want to manually perform the back button in your Activity or Fragment, just simply call:
设置覆盖默认行为的能力:
(调用
setUpbackpressedhandling()
来自活动increate()
):全局扩展功能:
To set up ability to override default behaviour:
(call
setupBackPressedHandling()
From ActivityonCreate()
):Global extension function:
活动:java
删除onbackpressed()
添加依赖项
实现'androidx.AppCompat:AppCompat:1.6.1'
在您的OnCreate方法中
onbackinvokeddispatcher.registeronbackinvokedcallback for API级别33+
backword兼容性的API
级别13+“
Activity : Java
Remove onBackPressed()
Add dependencies
implementation 'androidx.appcompat:appcompat:1.6.1'
In your onCreate method
onBackInvokedDispatcher.registerOnBackInvokedCallback for API level 33+
onBackPressedDispatcher callback for backword compatibility "API
level 13+"
覆盖底部表的ondismiss()函数。
override the onDismiss() function for BottomSheets.
如果您要覆盖onbackpressed(),但是如果要调用此方法,
使用此代码,您会发现:
onbackpresseddispatcher.onbackpressed()
if you're overriding the onBackPressed() its okay but if you want to call this method,
use this code and you'll find:
onBackPressedDispatcher.onBackPressed()
这是一个最新的答案。您可以在此处找到文档( https://codelabs.developers.google.google.google.google 。下面将代码添加到主活动内部的OnCreate()中。除非您的项目需要其他用法,否则请参考文档。
Here is a more recent answer. You can find the documentation here(https://codelabs.developers.google.com/handling-gesture-back-navigation#4). Below add the code to your onCreate() inside main Activity. Unless your project requires other usage, reference the documentation.
对于使用 Jetpack导航的片段,您可以创建一个扩展功能,该功能将处理 Back 和 up 按事件。
后压 - >这是按手势导航按下按钮的动作或软背按钮
up按下 - >这是将导航中的后退按钮按下访问栏左上方的动作。它的全局ID是
android.r.id.home
fragmentExtension.kt
homefragment.kt
这将使处理后/向上按下没有任何麻烦的清洁片段。
For fragments using Jetpack navigation you can create an extension function, which will handle both the back and up press events.
Back press -> It is the action of pressing button by gesture navigation or soft back button
Up press -> It is the action of pressing the back button in navigation to top left of the access bar. Its global id is
android.R.id.home
FragmentExtension.kt
HomeFragment.kt
This will give the ability to handle the back/up press with cleaner fragments without any hassle.
使用下面的使用,
现在创建该方法来处理返回事件
!
Use like below,
and now create that method for handling back event
That's it!
用以下代码替换
onbackpressed()
。Kotlin
Java
Replace
onBackPressed()
with the below code.Kotlin
Java
根据您的API级寄存器:
至少需要使用
AppCompat:1.6.0-Alpha03
;电流是1.6.0-Alpha04
:更新:
感谢@ianhanniballake评论;您可以只使用
onbackpresseddispatcher
即使在API级别33+中因此,您可以做:
请注意,您不应覆盖
onbackpressed()
onbackpresseddispatcher
不发火的回调;检查此答案 澄清了这一点。According your API level register:
onBackInvokedDispatcher.registerOnBackInvokedCallback
for API level 33+onBackPressedDispatcher
callback for backword compatibility "API level 13+"This requires to at least use
appcompat:1.6.0-alpha03
; the current is1.6.0-alpha04
:UPDATE:
Thanks to @ianhanniballake comment; you can just use
OnBackPressedDispatcher
even in API level 33+So, you can just do:
Note that you shouldn't override the
onBackPressed()
as that will make theonBackPressedDispatcher
callback not to fire; check this answer for clarifying that.只需替换
为
更新
覆盖fun onbackpressed()
被弃用的,用以下代码替换为:将上述代码添加到活动生命周期函数中,例如
oncreate(savedinstancestate:)
。Simply replace
with
Update
Given that
override fun onBackPressed()
is deprecated, replace it with the following code:Add the above code to an activity lifecycle function like
onCreate(savedInstanceState:)
.结合了最高答案。这是一个解决方案:
1。当您需要按下后按钮时,请复制以下内容:
注意:它将自动破坏您的活动。
2。当您需要按下后面按钮时,请复制以下内容:
With a combination of top answers. Here is a solution :
1. When you need to press the back button, copy this :
Note: it will automatically destroy your activity.
2. When you need to handle the back button pressed, copy this :
在 kotlin 中,这样可以工作
1-删除
onbackpressed()
2-下面
oncreate(savedinstancestate:bundle:bundle?)
添加以下行:3--定义用于处理的新功能
In Kotlin, this way is working
1- Remove
onBackPressed()
2- below
onCreate(savedInstanceState: Bundle?)
add these lines:3- Define a new function for handling
您可以使用
inbackpresseddispatcher
You could use the onBackPressedDispatcher
in here "this" means the lifeCycleOwner
对于Kotlin用户:
如果您尝试使用“新”方式调用默认的本机回到按钮函数,则可以在活动中使用代码波纹管。
示例:
上面的示例在按钮内设置了单击功能,以使按钮的作用像本机Android Back按钮。
但是,如果您想自定义OnbackpressedDisPatcher,则可以按照示例bellow,始终在您的活动中,因为此行为需要活动上下文才能工作。
自定义的Onbackpressed:
预期的结果是使任何onbackpresseddispatcher事件都做任何您想做的事情,或者根本不做任何事情。但这不建议这样做,因为您的用户可能会卡在屏幕上,而无需使用手机的后退按钮。因此,避免将handeronbackpressed卸载为空。因此,尝试这样的事情:
For Kotlin Users:
If you are trying to call the Default Native Back Button function using the 'new' way, you can use the code bellow inside your Activity.
example:
The example above sets a click function inside a button, to make the button act like the Native Android Back Button.
However, if you want to customize the onBackPressedDispatcher, you can follow the example bellow, always inside your Activity, because this behaviour needs an Activity Context to work.
Example of Customized OnBackPressed:
The expected result is to make any onBackPressedDispatcher event to do whatever you want, or do nothing at all. But this is not recommended, since your user might get stuck in a screen, without being able to use his Phone's Back Button. Because of that, avoid leaving handleOnBackPressed override empty. So try something like this:
使用onbackpresseddispatcher.onbackpressed()而不是super.onbackpresse()
use onBackPressedDispatcher.onBackPressed() instead of super.onBackPressed()
大多数答案是在要关闭活动时调用
finish()
。在大多数情况下,这很好,但是在某些情况下这不起作用。例如,在Android 13中,当您按下堆栈中的最后一个活动并返回主屏幕时,ondestroy()
in to n in tocy> indestroy()均未立即调用,并且应用程序保留在内存中。如果您再次打开应用程序,则它是从onstart()
开始的。因此,在某些情况下,最好让系统处理应用程序的关闭,换句话说,让
super.onbackpresse()
发生。要替换此
操作 -
如果您将回调添加到
onbackPressedDisPatcher
,并调用onbackPressedDispatcher.onbackpresse()
,它总是调用thenge> handerbackpresse()
。一旦完成后,就没有诸如OnSuperBackpress()之类的方法或可以让系统知道的一些方法。如果您不添加回调,则系统会执行自己的操作,但是如果您添加了回调,则调用onbackpress将调用handleonbackpresse()
。因此,我们要做的是,一旦您完成了后盖,您callback.remove()
回调就会自行删除自身,现在进行onbackpresspressepressedispatcher.onbackpresse(),它不会调用
handleonbackpressed()
并按照系统的方式处理后盖,这等同于super.onbackpresse()
。Most answers are calling
finish()
when you want to close the activity. This works fine for most cases but in some situations this doesn't work. For example, in Android 13, when you press back on the last activity in the stack and return to the home screen,onDestroy()
is not called immediately and app remains in memory. If you open up the app again right then, it starts fromonStart()
.So, in some situations its better to let the system handle the closing of the app, or in the other words, let
super.onBackPressed()
happen.To replace this
do this -
If you add a callback to the
onBackPressedDispatcher
, and callonBackPressedDispatcher.onBackPressed()
, it always callshandleOnBackPressed()
. There is no method like onSuperBackPressed() or something to let the system know to handle the backPress on its own once you're done. If you don't add the callback, then the system does its own thing, but if you've added it, then calling onBackPress will invokehandleOnBackPressed()
. So what we do is, once you're done handling the back-press, youcallback.remove()
the callback removes itself and now when you doonBackPressedDispatcher.onBackPressed()
, it will not invokehandleOnBackPressed()
and handle the back-press as the system would do, which is equivalent tosuper.onBackPressed()
.您可以使用onbackinvokedCallback
You can use the OnBackInvokedCallback
您可以使用onbackpresseddispatcher。在一个示例下:
you can use onBackPressedDispatcher. Below an example: