ListView滚动到底部自动加载数据
来源:程序员人生 发布时间:2014-12-19 08:16:01 阅读次数:4303次
在Android中有很多时候会选择用ListView加载数据,有的是分批加载,比如每次加载20条,100条就要加载5次,如果1次性加载100条,ListView加载就会变慢,如果是有图片的话,1是浪费流量,2是item中带图片会出现错位的问题l,ListView加载数据目前好多App的做法
1. 分批加载,滑动到底部自动更新
2. 滑动到底部,手动的点击加载更多
3. 下拉刷新 + 底部加载更多
今天实现ListView滑动到底部自动更新的效果。
原理:监听ListView的滑动事件,判断ListView是不是滑动到底部,然后去加载数据。
-
public class MainActivity extends Activity {
-
private ListView listview;
-
private List<String> datas;
-
private LayoutInflater inflater;
-
private MyAdapter adapter;
-
private List<String> contents;
-
private int count = 0;
-
private View footView;
-
private Handler handler = new Handler();
-
int lastItem;
-
private RelativeLayout loading;
-
@Override
-
protected void onCreate(Bundle savedInstanceState) {
-
super.onCreate(savedInstanceState);
-
setContentView(R.layout.activity_main);
-
initData();
-
inflater = LayoutInflater.from(this);
-
listview = (ListView) findViewById(R.id.listview);
-
adapter = new MyAdapter();
-
footView = inflater.inflate(R.layout.footer, null);
-
loading = (RelativeLayout) footView.findViewById(R.id.loading);
-
-
listview.addFooterView(footView);
-
listview.setAdapter(adapter);
-
-
listview.setOnScrollListener(new OnScrollListener() {
-
-
@Override
-
public void onScrollStateChanged(AbsListView view, int scrollState) {
-
if (scrollState == OnScrollListener.SCROLL_STATE_IDLE) {
-
if (view.getLastVisiblePosition() == view.getCount() - 1) {
-
loadData();
-
}
-
}
-
}
-
@Override
-
public void onScroll(AbsListView view, int firstVisibleItem,
-
int visibleItemCount, int totalItemCount) {
-
lastItem = firstVisibleItem + visibleItemCount - 1 ;
-
}
-
});
-
}
-
protected void loadData() {
-
loading.setVisibility(View.VISIBLE);
-
handler.postDelayed(new Runnable() {
-
@Override
-
public void run() {
-
load();
-
loading.setVisibility(View.GONE);
-
adapter.notifyDataSetChanged();
-
}
-
}, 5000);
-
}
-
protected void load() {
-
int count
= adapter.getCount() + 1;
-
for(int i
= count; i < count + 20; i++) { //每次加载20条数据
-
contents.add("加载数据:::" +
i);
-
}
-
}
-
private void initData() {
-
contents = new ArrayList<String>();
-
for(int i
= 1; i < 20;
i++){
-
contents.add("加载数据:::" +
i);
-
}
-
}
-
-
class MyAdapter extends BaseAdapter{
-
@Override
-
public int getCount() {
-
return contents.size();
-
}
-
@Override
-
public Object getItem(int position) {
-
return contents.get(position);
-
}
-
-
@Override
-
public long getItemId(int position) {
-
return position;
-
}
-
-
@Override
-
public View getView(int position, View convertView, ViewGroup parent) {
-
ViewHolder holder;
-
if(convertView
==
生活不易,码农辛苦
如果您觉得本网站对您的学习有所帮助,可以手机扫描二维码进行捐赠