onViewCreated叫了两声(onViewCreated called twice)

2019-10-28 12:17发布

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

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

Answer 1:

这个问题上升下面一行:

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

LocationSelectorActivity.newIntent(上下文)必须被替换为:

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



文章来源: onViewCreated called twice