onViewCreated调用了两次

时间:2018-08-24 09:44:38

标签: android android-fragments kotlin

我内部有一个活动和片段,我打开第二个活动以获取片段的结果:

startActivityForResult(LocationSelectorActivity.newIntent(context!!), START_LOCATION_SELECTOR) 

如果我在用户离开活动时强制死亡(通过开发人员选项),则在我的第二次活动中对onViewCreated进行的后单击会在我的fragmetn中被调用两次

 override fun onViewCreated(view: View, savedInstanceState: Bundle?)

这是我添加片段的方式:

 override fun onCreate(savedInstanceState: Bundle?) {
        super.onCreate(savedInstanceState)

        addFragment(MyFragment(), R.id.content_frame)
    }


fun AppCompatActivity.addFragment(fragment: Fragment, frameId: Int) {
    supportFragmentManager.inTransaction { add(frameId, fragment) }
}

1 个答案:

答案 0 :(得分:-2)

问题出现在以下行:

startActivityForResult(LocationSelectorActivity.newIntent(context!!), START_LOCATION_SELECTOR)

LocationSelectorActivity.newIntent(context)必须替换为:

Intent intent = new Intent(/*your desirable configiration*/);
getActivity().startActivityForResult(intent, START_LOCATION_SELECTOR);

Intent intent = new Intent(/*your desirable configiration*/);
startActivityForResult(intent, START_LOCATION_SELECTOR);

然后在您的主机活动或片段覆盖onActivityResult()方法中