Reputation: 18343
My activity contains "FrameLayout" element only.
In its 'onCreate' method I dynamically load fragment:
@Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
UsersListFragment fragment = new UsersListFragment();
FragmentManager fm = getSupportFragmentManager();
FragmentTransaction ft = fm.beginTransaction();
ft.add(R.id.fragment_container, fragment);
ft.commit();
}
On some event my fragment communicates back to activity and I need to instantiate another fragment and pass some data to it. I do it in the activity by implementing special interface that is in turn called by fragment. It looks like this way:
@Override
public void onUserSelected(long userId) {
UserDetailsFragment fragment = new UserDetailsFragment();
FragmentManager fm = getSupportFragmentManager();
FragmentTransaction ft = fm.beginTransaction();
ft.replace(R.id.fragment_container, fragment);
ft.addToBackStack(null);
ft.commit();
fragment.updateUser(userId);
}
As a result, "fragment.updateUser(userId);" is called way to early (fragment is not initialized yet, it is not attached to activity).
Question: what is the proper way to pass data into the fragment?
Thanks a lot in advance. Any thoughts are greatly appreciated.
P.S. I've seen a lot of examples that show how to load fragments, but was not able to find those that show how to pass data...
Upvotes: 0
Views: 2101
Reputation: 18343
That usually happens to me: once wrote a question I got a new idea to try...
Looks like one of the possible options is to pass data by setting them via 'setArguments' method... and use during 'onCreateView' fragment method...
Any better options?
Upvotes: 1