I have a fragment which creates its view inside onCreateView as you'd expect. However I want to change the view periodically.
My use case is that the fragment shows some data from a web service. When a user chooses an option from a list (another fragment), this fragment should switch to a progress bar, then once loaded, switch back to the data view.
I could make two fragments - the loading fragment, and the displaying fragment, but it seems that since this is an encapsulated event I'd rather do it all inside the one fragment.
Basically what I am asking, is what is the equivilent of setContentView inside a fragment.
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.
You can use Fragment.getView()
. This returns the view of the container which contains the Fragment
. On that view, you can call removeAllViews
. Then build your new views and add them to the view you got from getView()
.
http://developer.android.com/reference/android/app/Fragment.html#getView()
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With