转自:http://blog.csdn.net/shineflowers/article/details/41744241
在Android中有很多时候会选择用ListView加载数据,有的是分批加载,比如每次加载20条,100条就要加载5次,如果一次性加载100条,ListView加载就会变慢,如果是有图片的话,一是浪费流量,二是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()添加view到listview底部一定要加在listview.setAdapter(adapter);这代码前面 listview.addFooterView(footView); listview.setAdapter(adapter); //添加listview滚动监听 listview.setOnScrollListener(new OnScrollListener() { //AbsListView view 这个view对象就是listview @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++){ 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==null){ convertView = inflater.inflate(R.layout.item, parent, false); holder = new ViewHolder(); holder.tvContent = (TextView) convertView.findViewById(R.id.tvContent); convertView.setTag(holder); }else{ holder = (ViewHolder) convertView.getTag(); } holder.tvContent.setText(contents.get(position)); return convertView; } class ViewHolder{ TextView tvContent; } } }
时间: 2024-10-25 11:07:10