App open on first fragment and there is 2 tabs i want to refresh second fragment when i move to it but i don\'t want to refresh first fragment
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();
}
}
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
Try This
ViewPager mViewPager = (ViewPager)findViewById(R.id.pager);
mViewPager.setOffscreenPageLimit(2);
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
}
}
If you wouldn't mind refreshing every fragment every time a tab changes, you could simply override the getItemPosition()
method of your FragmentPagerAdapter and make it return always the value POSITION_NONE
. Example:
@Override
public int getItemPosition(Object object) {
return POSITION_NONE;
}
By doing that, you tell android to refresh the fragment each time the view pager tries to get it. Performance wise, it isn't the best practice. So there is a second approach:
First, create an interface to be called when your need refresh:
public interface Updatable {
public void update();
}
Then, make your fragments implement this interface:
public class MyFragment extends Fragment implements Updateable {
...
@Override
public void update() {
// refresh your fragment, if needed
}
}
If your really wish to not update your first fragment, do nothing in its update()
method.
Third, override the getItemPosition
method and call update()
. This will be called every time a fragment gets selected:
@Override
public int getItemPosition(Object object) {
Updatable f = (Updatable) object;
if (f != null) {
f.update();
}
return super.getItemPosition(object);
}
Most of this code came from this answer.