我正在用Kotlin开发一个Android应用程序,所以...
上下文: 我有一个activity(A),而不是一个viewPager,该viewPager包含2个片段(F1,F2),其中一个片段(F1)还有另一个2个片段(CF1,CF2)
问题是,当我从片段(CF1)调用活动(B)forResult时,活动(A)从活动(B)接收结果,然后传递给片段(F1),但从不接收fragment(CF1)
val intent = Intent(activity, B::class.java)//how i call activity(B) so good
intent.putExtra("select",1)
//parentFragment!!.startActivityForResult(intent, REQ_CODE)//
startActivityForResult(intent, REQ_CODE)
//how i receive on Activity(A) so good
public override fun onActivityResult(requestCode: Int, resultCode: Int, data: Intent) {
for(i in 0..adapterNormal.COUNT){
var f = adapterNormal.getItem(i)
f?.onActivityResult(requestCode,resultCode,data)
}
}
//how i receive on fragment(F1) so good
override fun onActivityResult(requestCode: Int, resultCode: Int, data: Intent?) {
super.onActivityResult(requestCode, resultCode, data)
if(resultCode == RESULT_OK){
cli_name = data!!.getStringExtra("clie_name")
cli_id = data.getStringExtra("clie_id")
}
}
//how i tried to receive on fragment(CF1)
override fun onActivityResult(requestCode: Int, resultCode: Int, data: Intent?) {
super.onActivityResult(requestCode, resultCode, data)
Log.d("onActivityResult", "requestCode = $requestCode")
}
我试图简化问题,希望任何人都能帮助我。 谢谢。
答案 0 :(得分:0)
您没有调用CF1的onActivityResult函数。
调用super.onActivityResult足以将调用从Activity路由到Fragment,但不能将其路由到嵌套的Fragment(在这种情况下)。
因此,您应该明确地进行该调用:
片段F1:
override fun onActivityResult(requestCode: Int, resultCode: Int, data: Intent?) {
super.onActivityResult(requestCode, resultCode, data)
if(resultCode == RESULT_OK){
cli_name = data!!.getStringExtra("clie_name")
cli_id = data.getStringExtra("clie_id")
}
cf1?.onActivityResult(requestCode, resultCode, data)
}
答案 1 :(得分:0)
问题是,当我从fragment(CF1)为Result调用activity(B)时,activity(A)从activity(B)接收结果,然后传递给fragment(F1),但从未在fragment(CF1)上接收)
在片段(CF1)中,使用startActivityForResult
val intent = Intent(context, B::class.java)
intent.putExtra("select",1)
startActivityForResult(intent, REQ_CODE)
不要在活动中实施onActivityResult
,也请仅在片段(CF1)中实施
override fun onActivityResult(requestCode: Int, resultCode: Int, data: Intent?) {
when (requestCode) {
REQ_CODE -> when (resultCode) {
RESULT_OK -> {
//do your work here
}
}
}
}
这在我的项目中运行良好。
请不要忘记在您的活动(B)
中致电setResult(Activity.RESULT_OK)