onViewCreated called twice

2019-09-04 18:04发布

问题:

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

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

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

回答1:

The problem rises in following line:

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

LocationSelectorActivity.newIntent(context) must be replaced by:

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

or

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

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