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

3

7

So I have this piece of code here, I am creating a new Fragment and replacing it with another fragment. That works well. However I have notice that on the first line the constructor is being called but the onAttach(), onCreate() etc are not. If I were to uncomment the second line it won't work as updateItem(URL) requires a webView that is initiated in the onCreate() function.

DetailViewFragment detailFragment = new DetailViewFragment();
//detailFragment.updateItem(URL);
FragmentTransaction ft = getFragmentManager().beginTransaction();
ft.replace(R.id.displayList, detailFragment);
ft.setTransition(FragmentTransaction.TRANSIT_FRAGMENT_FADE);
ft.addToBackStack(null);
ft.commit();

Would appreciate any help that will get that to work with the second line uncommented.

Fever answered 25/7, 2014 at 12:38 Comment(1)
I believe that onAttach, onCreate, etc don't get called until the fragment has been committed to the Activity. So they should be called on the last line of that code. Android docs on lifecycle: developer.android.com/reference/android/app/… Have you tried using ft.add(...)?Acceptation
G
4

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.

Grayish answered 25/7, 2014 at 13:5 Comment(0)
D
4

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);
}
Disjunctive answered 20/9, 2015 at 15:38 Comment(0)
E
0

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

Eraser answered 2/10, 2015 at 11:58 Comment(0)

© 2022 - 2024 — McMap. All rights reserved.