Replacing fragments in an activity not calling onAttach, onCreate, onCreateView, etc

坚强是说给别人听的谎言 提交于 2019-12-05 04:26:25

The onAttach(), onCreate(), etc. will not be called until the FragmentManager has actually committed the change. So, some time after commit() is called on the transition. If you need to pass the URL to the Fragment from the start, add it to the fragment's argument bundle before you call commit(). Then you'll be able to get access to the URL in your onCreate() or other lifecycle methods. So you'll want something like this:

DetailViewFragment detailFragment = new DetailViewFragment();
Bundle args = new Bundle();
args.putString(DetailViewFragment.INIT_URL, URL);
detailFragment.setArguments(args);
ft.replace(R.id.displayList, detailFragment);
ft.setTransition(FragmentTransaction.TRANSIT_FRAGMENT_FADE);
ft.addToBackStack(null);
ft.commit();

Now in your onCreate() you can call getArguments() to get the bundle and retrieve the URL which was passed by your activity.

API Level 23 onAttach(Context context) works
API Level 22 onAttach(Activity activity) works

Implementing both methods worked for me:

@Override
public void onAttach(Context context) {
    super.onAttach(context);
}

@Override
public void onAttach(Activity activity) {
    super.onAttach(activity);
}

Another solution would be to call getSupportFragmentManager().executePendingTransactions(); just after the commit. Beware that the transcation will be synchronous then.

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!