今天闲来无事,
就测试了一下listview加载图片优化的功能,
在我们使用新浪微博的时候,细心的同学一定发现了,在滑动的过程中,图片是没有被加载的,
而是在滑动停止时,才加载图片了。
我们今天就做一个这样的效果吧。
我们先考虑两个问题:
1、在滑动停止的时候,如何获得需要加载的图片控件?
2、因为listiew在初始化完成的时候,OnScrollListener的onScrollStateChanged与onScroll并未被触发,如何初始化第一页的图片?
package com.test.list; import android.app.Activity; import android.os.Bundle; import android.util.Log; import android.view.View; import android.view.ViewGroup; import android.widget.AbsListView; import android.widget.AbsListView.OnScrollListener; import android.widget.BaseAdapter; import android.widget.ImageView; import android.widget.ListView; public class TestAndroidListActivity extends Activity { private int start_index, end_index; // 判断是否是初始化 private boolean isInit = false; private ListView list; @Override public void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.main); this.initList(); } private BaseAdapter adapter = new BaseAdapter() { @Override public View getView(int position, View convertView, ViewGroup parent) { // TODO Auto-generated method stub View v; if (convertView == null) { v = getLayoutInflater().inflate(R.layout.list_item, null); v.setTag(v); } else { v = (View) convertView.getTag(); ImageView iv = (ImageView) v.findViewById(R.id.img); iv.setImageResource(R.drawable.ic_launcher); } ImageView iv = (ImageView) v.findViewById(R.id.img); // 给图片控件设置上对应的位置编号 iv.setTag(position); if (!isInit) { iv.setImageResource(R.drawable.update_log); } return v; } @Override public long getItemId(int position) { // TODO Auto-generated method stub return 0; } @Override public Object getItem(int position) { // TODO Auto-generated method stub return null; } @Override public int getCount() { // TODO Auto-generated method stub return 140; } }; private void initList() { // TODO Auto-generated method stub list = (ListView) this.findViewById(R.id.list); list.setAdapter(adapter); list.setOnScrollListener(new OnScrollListener() { @Override public void onScrollStateChanged(AbsListView view, int scrollState) { // TODO Auto-generated method stub isInit = true; switch (scrollState) { case OnScrollListener.SCROLL_STATE_IDLE:// 滑动停止 for (; start_index < end_index; start_index++) { ImageView img = (ImageView) list.findViewWithTag(start_index); img.setImageResource(R.drawable.update_log); } break; default: break; } } @Override public void onScroll(AbsListView view, int firstVisibleItem, int visibleItemCount, int totalItemCount) { // TODO Auto-generated method stub // 设置当前屏幕显示的起始index和结束index start_index = firstVisibleItem; end_index = firstVisibleItem + visibleItemCount; } }); } }
其实很简单,大家可以研究研究,举一反三哈!