Refresh fragment when change between tabs
Try This
ViewPager mViewPager = (ViewPager)findViewById(R.id.pager);
mViewPager.setOffscreenPageLimit(2);
Inside Your fragment class use the below code:
@Override
public void setUserVisibleHint(boolean isVisibleToUser) {
super.setUserVisibleHint(isVisibleToUser);
if (isVisibleToUser) {
getFragmentManager().beginTransaction().detach(this).attach(this).commit();
}
}
When a Fragment
is made visible (i.e., the selected page in your ViewPager
), its setUserVisibleHint() method is called. You can override that method in your TwoFragment
and use it to trigger a refresh.
public class TwoFragment extends Fragment {
@Override
public void setUserVisibleHint(boolean isVisibleToUser) {
super.setUserVisibleHint(isVisibleToUser);
if (isVisibleToUser) {
// Refresh your fragment here
}
}
As of 2020 it is advisable to use architecture components(MVVM) such as LiveData and viewModel
This way all Fragments can share the same state
see docs here https://developer.android.com/jetpack/guide