Stop ViewPagers inside ListView from resetting

I have a ListView that contains ViewPager s strings. When a ViewPager scrolls from the screen, I want to keep its position on the page. When the user scrolls back to the ViewPager , I want to restore its last saved page position.

I am trying to execute this with the following code:

 public class MyBaseAdapter extends BaseAdapter { // Row ids that will come from server-side, uniquely identifies each // ViewPager private List<String> mIds = new ArrayList<String>(); private Map<String, Integer> mPagerPositions = new HashMap<String, Integer>(); @Override public View getView(int position, View convertView, ViewGroup parent) { String id = mIds.get(position); View rootView = convertView; if (rootView == null) { rootView = LayoutInflater.from(parent.getContext()).inflate( R.layout.row, null); } ViewPager viewPager = (ViewPager) rootView.findViewById(R.id.pager); Integer pagerPosition = mPagerPositions.get(id); if (pagerPosition != null) { viewPager.setCurrentItem(pagerPosition); } viewPager.setOnPageChangeListener(new MyPageChangeListener(id)); return rootView; } @Override public int getCount() { return mIds.size(); } @Override public Object getItem(int position) { return null; } @Override public long getItemId(int position) { return 0; } private class MyPageChangeListener extends ViewPager.SimpleOnPageChangeListener { private String mId; public MyPageChangeListener(String id) { mId = id; } @Override public void onPageSelected(int position) { mPagerPositions.put(mId, position); } } } 

The page position is saved the first time setPagerPosition() called. Subsequently, when the ViewPager goes beyond the bounds of the screen, onPageSelected() is called with the first position of the page saved - overwriting any previous onPageSelected() calls that occurred while the ViewPager was still visible.

What is the right way to do this?

+6
source share
2 answers

The solution was to not overwrite the position of the pager when the ViewPager is not displayed. It seems to be a bug in Android, where onPageSelected is called when the ViewPager is disabled when scrolling through the ListView.

 @Override public void onPageSelected(int position) { if (viewPager.isShown()) { mTopicPositions.put(mId, position); } } 
+3
source

I think you can get the current displayed position on indexOfChild(viewPager.getFocusedChild()) and save it according to general preference and can retrieve it when necessary. Hope this helps

0
source

All Articles