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?
source share