Answer the question
In order to leave comments, you need to log in
How to make an infinite ViewPager with three items in Android?
The task is to implement “endless” page scrolling using ViewPager and PagerAdapter. The elements are View (not Fragment). All views are created from a single xml-layout via inflater, they differ only in content. The content is loaded from the API.
In the ViewPager parameters, I set a limit on the limit of inactive pages on the left and right:mViewPager.setOffscreenPageLimit(1);
Thus, 1 active page can be stored at the same time and 1 on the left and on the right, if there are more of them, the corresponding page is called. deletion method in PagerAdapter-e. At startup, there is 1 id for which content is loaded from the Internet with API (image + text). After loading the first page, the api sends a response with the id of the next page, if any. I store page id-shniks in ArrayList: when creating an adapter, I initialize this list with the first value (id of the initial page), when I get the next id, I add the following value there. It turns out that at startup I have an adapter whose getCount returns the size of this id array (mPagesId), at the beginning it is 1. Next, the adapter requests the 0th position for the ViewPager:
@Override
public Object instantiateItem(ViewGroup collection, int position) {
int pageId = Integer.valueOf(mPagesId.get(position));
View newView = createNewView();
newView.setId(pageId);
((ViewPager) collection).addView(newView);
// start post loading if there is active network connection
if (ConnectionUtils.isOnline(mContext)) {
TaskLoadPost loadPostTask = new TaskLoadPost();
loadPostTask.execute(pageId);
} else {
DialogUtil.showNetworkErrorDialog((Activity) mContext);
}
return newView;
}
mPagesId.add(id);
((ViewPager) collection).removeView((View) view);
View page = (View) view;
mPagesId.remove(String.valueOf(page.getId()));
notifyDataSetChanged();
Answer the question
In order to leave comments, you need to log in
Didn't find what you were looking for?
Ask your questionAsk a Question
731 491 924 answers to any question