If for any reason, you want to change the whole fragment view (for example, asynchronous URL request that will change the view on success), you can either use the FragmentTransaction in the parent activity and create a new fragment on the fly.
Or you can keep the fragment and call a method of this fragment that will refresh itself.
Example:
In the parent activity, I build and store a list of fragments List<RefreshFragment> mFragmentList
.
Here is the RefreshFragment class (and all my fragments extend this one in my example) :
public class RefreshFragment extends Fragment {
protected Data data; // here your asynchronously loaded data
public void setData(Data data) {
this.data = data;
// The reload fragment code here !
if (! this.isDetached()) {
getFragmentManager().beginTransaction()
.detach(this)
.attach(this)
.commit();
}
}
}
Then in my activity asynchronous callback I can call :
for (RefreshFragment f : mFragmentList) f.setData(data);
So every fragment will be updated with the correct data and the currently attached fragment will update itself immediately. You have to provide you own onCreateView in the fragments of course.
The important thing is that a fragment can reload itself with getFragmentManager()
.
Nowdays, I would suggest using ViewModel
for that purpose.