[英]Android How can I have a ViewPager where the number of pages is determined by ASyncTask
I have an activity which has a ViewPager on it. 我有一个活动,上面有一个ViewPager。 I would like to have one page in the pager for every item returned from a server call using an AsyncTask.
我想在寻呼机中为使用AsyncTask从服务器调用返回的每个项目提供一页。
My server call is a paginated call, so the first time i call the server i ask for items 1 through 10. I then want my ViewPager to have a page for each of these 10 items and i can swipe left and right through the pages. 我的服务器呼叫是分页呼叫,因此,第一次呼叫服务器时,我会询问项目1到10。然后,我希望ViewPager拥有这10个项目中的每一个的页面,并且我可以在页面中左右滑动。 When i swipe to the 10th page, i want to call the server to get the next 10 pages (ie pages 11 through 20) so that on the 10th page i can swipe to get to page 11.
当我滑动到第10页时,我想调用服务器以获取下一个10页(即第11到20页),以便在第10页上可以滑动到第11页。
I see a lot of examples online for how i can use an AsyncTask to get the contents of a single " ViewPager page's fragment ", but this is not what i want, I want the AsyncTask to determine the " number of pages in the pager " (by returning a list of data objects containing information to display on each page). 我在网上看到很多示例,这些示例说明了如何使用AsyncTask来获取单个“ ViewPager页面的片段 ”的内容,但这不是我想要的,我希望AsyncTask确定“ pager中的页面数 ” (通过返回包含要在每个页面上显示的信息的数据对象的列表)。
This is simple with lists and ListAdapters, but i can not work out how to do this with ViewPagers and PagerAdapters. 这对于列表和ListAdapters很简单,但是我不知道如何使用ViewPagers和PagerAdapters做到这一点。
Any help would be greatly appreciated. 任何帮助将不胜感激。
I appear to have got this working in a very basic state. 我似乎已经在一个非常基本的状态下进行了这项工作。
DataManager I have a DataManager which is responsible for getting the items from the server using a ASyncTask DataManager我有一个DataManager,它负责使用ASyncTask从服务器获取项目
PagerAdapter 页面适配器
The PagerAdapter is as follows PagerAdapter如下
class MyPageAdapter extends FragmentPagerAdapter {
// Members
....
private DataManager dataManager;
// create an observer to listen for changes in the data manager
private final DataSetObserver observer = new DataSetObserver() {
@Override
public void onChanged() {
Toast.makeText(appCtx(), "MyPagerAdapter observer's onChanged called", Toast.LENGTH_LONG).show();
// Notify observers on this adapter that item list has changed.
notifyDataSetChanged();
}
};
// constructor
public MyPageAdapter(DataManager dataManager, .....) {
super(fm);
this.dataManager = dataManager;
dataManager.registerDataSetObserver(observer);
}
/**
* Get the number of items from the manager
*/
private int getSize() {
return dataManager.size();
}
// get the item for the given position
@Override
public Fragment getItem(int position) {
// if the next item is not available the managers task will get the next batch
dataManager.ensureItemAvailable(position+1);
// get this position's item from the data manager and create a fragment using that item
Object obj = dataManager.getItem();
return MyPagerFragment.newInstance(obj);
}
....
....
}
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.