ActivityResultContracts.StartActivityForResult() 结果仅调用一次
当使用 androids 新的活动结果 API 时,回调仅对我触发一次。
class MyFragment : Fragment() {
private val intentLauncher = registerForActivityResult(ActivityResultContracts.StartActivityForResult()) { result: ActivityResult ->
if (result.resultCode == Activity.RESULT_OK) {
...
}
}
}
private fun onClick(id: Long) {
val intent = Intent(context, MyActivity::class.java)
intent.putExtra(MyActivity.ID_EXTRA, id)
intentLauncher.launch(intent)
}
第一次单击片段会启动活动,活动完成后结果会正确传回。但是,当片段再次启动活动时,活动会设置结果并调用完成。但是,片段中的结果回调不会再次触发。
还注意到我不需要包括:
implementation 'androidx.activity:activity-ktx:1.4.0'
implementation 'androidx.fragment:fragment-ktx:1.4.1'
新的活动结果 API 是否附带一些其他依赖项?想知道我正在引入的版本是否还发生了其他奇怪的事情?
编辑:
需要注意的是,只有在使用片段中的新活动结果 api 启动新活动时才会发生这种情况。从活动启动时我没有看到相同的行为。我需要对片段做一些不同的事情吗?
When using androids new activity result API, the callback is only firing once for me.
class MyFragment : Fragment() {
private val intentLauncher = registerForActivityResult(ActivityResultContracts.StartActivityForResult()) { result: ActivityResult ->
if (result.resultCode == Activity.RESULT_OK) {
...
}
}
}
private fun onClick(id: Long) {
val intent = Intent(context, MyActivity::class.java)
intent.putExtra(MyActivity.ID_EXTRA, id)
intentLauncher.launch(intent)
}
On first click the fragment launches the activity, and on activity finish the result is passed back correctly. However when the fragment launches the activity again, the activity sets the result and calls finish. However the result callback in the fragment is not fired again.
Also noticed that I didn't need to include:
implementation 'androidx.activity:activity-ktx:1.4.0'
implementation 'androidx.fragment:fragment-ktx:1.4.1'
Does the new activity result API come along with some other dependency? Wondering if something else weird is going on w/ the versions I am pulling in?
EDIT:
Its important to note that this is only happening when using the new activity result api from a fragment to launch a new activity. I do not see the same behavior when launching from an activity. Is there something I need to do differently for fragments?
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(1)
只需在
startActivityForResult()
之前添加launchIntent.setFlags(0);
即可。<一href="https://stackoverflow.com/questions/7910840/android-startactivityforresult-immediately-triggering-onactivityresult/24312398#:%7E:text=You%20can%27t%20use%20startActivityForRes ult()%20if%20your%20activity%20is%20being%20launched%20as%20a%20singleInstance%20or%20singleTask.%20standard%20or%20singleTop%20launch%20mode%20will%20fix%20the%20问题。">这个参考可能对你有帮助。
Just add
launchIntent.setFlags(0);
beforestartActivityForResult()
.This reference may help you.