I have a fragment that inflates an xml layout. My requirement is to update the text size on all my views inside my fragment when my Activity is resumed. I tried
fragment.getView().invalidate();
which didn't seem to do the work. I also tried
fragment.getView().requestLayout();
which didn't work either.
On another activity, I have a ListFragment which needs to do the same thing. I tried
listfragment.getListView().invalidate();
which did the trick, refreshing my list view and redrawing all the items inside it.
I don't understand why one works but not the other.
I have also seen people recommending initiating a fragment transaction and replacing the current fragment with a new one, and it has kept me wondering
Why should I create a whole new fragment and replace my current fragment when all I need is to refresh the text on the views that my fragment contains.
Fragment transaction method will prevent me from defining my fragment in the layout xml of my activity and I will have to programatically insert the fragment at the right position.
Is there any simple approach to this?
The onResume() get called always before the fragment is displayed. Even when the fragment is created for the first time . So you can simply move your from onViewCreated() to onResume .
So when you click your Button , find the Fragment you want to refresh by its tag, and then call your refresh method.
Calling a textView. setText(newText) should and does invoke invalidate() on its own (possibly also requestLayout() in certain cases which invokes invalidate() ), so you shouldn't need to manually call postInvalidate() unless you are custom-rendering with a Canvas.
OnPageChangeListener is the correct way to go, but you will need to refactor your adapter a bit in order to keep a reference to each Fragment contained in the FragmentPagerAdapter. Then, instead of creating a new Fragment, use the one contained in the adapter: mViewPager. addOnPageChangeListener(new ViewPager.
I do not think there is a method for that. The fragment rebuilds it's UI on onCreateView()... but that happens when the fragment is created or recreated.
You'll have to implement your own updateUI method or where you will specify what elements and how they should update. It's rather a good practice, since you need to do that when the fragment is created anyway.
However if this is not enough you could do something like replacing fragment with the same one forcing it to call onCreateView()
FragmentTransaction tr = getFragmentManager().beginTransaction(); tr.replace(R.id.your_fragment_container, yourFragmentInstance); tr.commit()
NOTE
To refresh ListView you need to call notifyDataSetChanged()
on the ListView's adapter.
In my case, detach
and attach
worked:
getSupportFragmentManager() .beginTransaction() .detach(contentFragment) .attach(contentFragment) .commit();
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