onViewCreated调用了两次

onViewCreated调用了两次

本文介绍了onViewCreated调用了两次的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

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

I have one activity and fragment inside, I open second activity for result from my fragment :

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

如果我在用户离开活动时强制死亡(通过开发人员选项),则在我的第二次活动中,在我的fragmetn中两次调用了onViewCreated的后退按钮

If i force activity for die when user will leave it ( from developer option) , after back click from my second activity onViewCreated is called twice in my fragmetn

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

这是我添加片段的方式:

Here is how I add fragment :

 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) }
}

推荐答案

问题出现在以下行:

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

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

LocationSelectorActivity.newIntent(context) must be replaced by:

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()方法

then in your host activity or the fragment override onActivityResult() method

这篇关于onViewCreated调用了两次的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!

08-04 15:12