前言
项目中我们可能会加载列表数据,点击列表进入图片浏览,一般情况就是朋友圈动态,点击九宫格图片,进入大图预览页面,但是如果假设我们产品经理要求将列表图片进行ViewPager左右滑动的话,那么我们就得进行分页加载了,因为列表数据可能存在成千条。
正题
我们知道ViewPager可以通过addOnPageChangeListener()方法监听我们滑动哪一页,那么设想我们知道我们的数据totalCount=1000,每页加载10条,当我滑动到10条的时候我们就需要去请求下一页数据,依次类推,我们的数据如果小于totalCount,并且我们滑动的条目正好是当前页的最后一条,那么我们就需要去加载更多。
-代码如下
package com.wj.viewpagertransfroms;
import android.app.assist.AssistStructure;
import android.content.Context;
import android.support.v4.view.PagerAdapter;
import android.support.v4.view.ViewPager;
import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.TextView;
import java.util.ArrayList;
import java.util.List;
public class ViewPagerMoreActivity extends AppCompatActivity {
private ViewPager vp;
private List<String> list = new ArrayList<>();
private int limit = 10;
private int maxListCount = 30;
private MyAdapter adapter;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_view_pager_more);
vp = (ViewPager) findViewById(R.id.viewpager);
for (int i = 1; i <= 10; i++) {
list.add("第" + i + "页");
}
adapter = new MyAdapter(this);
vp.setAdapter(adapter);
vp.addOnPageChangeListener(new ViewPager.OnPageChangeListener() {
@Override
public void onPageScrolled(int position, float positionOffset, int positionOffsetPixels) {
}
@Override
public void onPageSelected(int position) {
int page = position + 1;
int size = list.size();
if (page < maxListCount && page == size) {
//在这儿加载更多模拟网络请求
for (int i = size + 1; i <= size + 10; i++) {
if (i > maxListCount){
return;
}
list.add("第" + i + "页");
}
adapter.notifyDataSetChanged();
}
}
@Override
public void onPageScrollStateChanged(int state) {
}
});
}
class MyAdapter extends PagerAdapter {
private Context context;
private LayoutInflater layoutInflater;
public MyAdapter(Context context) {
this.context = context;
layoutInflater = LayoutInflater.from(context);
}
@Override
public int getCount() {
return list.size();
}
@Override
public boolean isViewFromObject(View view, Object object) {
return view == object;
}
@Override
public Object instantiateItem(ViewGroup container, int position) {
View view = layoutInflater.inflate(R.layout.item_viewpager, null);
TextView tv_page = (TextView) view.findViewById(R.id.tv_page);
tv_page.setText(list.get(position));
container.addView(view);
return view;
}
@Override
public void destroyItem(ViewGroup container, int position, Object object) {
container.removeView((View) object);
}
}
}