Run code when the user of the viewpager fragment “swipes out”?
I need to detect when the
user slides in and out of one of my fragments, I tried onPause but it seems that the app doesn’t pause when sliding to an adjacent screen (it is broken when moving two sereens away from it). If possible, I’d like to start with the fragment itself, since I’m changing the fragment dynamically, and some of my code is only useful if a particular fragment exists.
Is this possible? How can I detect a slide “out” (if possible from the fragment itself)?
Edit:
I tried using setUserVisibleHint on Fragment and that seems to be the best way to do this, but it was never called. I’m using API level 19 and I’m not sure what’s missing :
import android.app.Fragment;
import android.os.Bundle;
import android.util.Log;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.Toast;
public class Contacts extends Fragment {
@Override
public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
View view = inflater.inflate(R.layout.fragment_screen_contacts, container, false);
return view;
}
@Override
public void setUserVisibleHint(boolean isVisibleToUser) {
super.setUserVisibleHint(isVisibleToUser);
Log.d("MyFragment", "This never shows up.");
Toast.makeText(getActivity(), "Neither does this", Toast.LENGTH_LONG).show();
}
}
Solution
You can use ViewPager#setOnPageChangeListener().
viewPager.setOnPageChangeListener(new OnPageChangeListener() {
...
@Override
public void onPageSelected(int position) {
do what you want here, for example
if (position != 3) {
...
}
}
});
Edit:
If you want the logic to be inside the Fragment itself, you can do this by adding a method onFragmentExited()
or another method to your subclass. Put the logic out there. The method is then called inside the OnPageChangeListener. For example:
viewPager.setOnPageChangeListener(new OnPageChangeListener() {
int lastPosition;
@Override
public void onPageSelected(int position) {
MyInterface fragment = (MyInterface)mPagerAdapter.instantiateItem(viewPager, lastPosition);
if (fragment != null) {
fragment.onFragmentExited();
}
/* If you want to notify the fragment being focused
fragment = (MiniApp)mPagerAdapter.instantiateItem(viewPager, position);
if (fragment != null) {
fragment.onFragmentEntered();
} */
lastPosition = position;
}
});
adapter.getFragment(position)
depends on whatever adapter/structure you use to store the fragment.