我的listview中有从互联网下载的图片。 我想在我的getView()中添加一些内容,以便在用户快速滚动/滚动时不下载图像?
我该如何开始这样做?
答案 0 :(得分:2)
您可以按照以下步骤延迟加载ListView中的视图。
首先,您应该制作ListView
对象和YOUR_COSTOM_ADAPTER_OBJECT
类变量。
然后,为ListView设置onScroll Listener
从ListView的onScroll Listener获取滚动速度:
从onScroll侦听器获取滚动速度,当速度变快时,告诉适配器不加载图像。
示例代码:
class YourClass extends Activity
{
YOUR_CUSTOM_LISTVIEW_ADAPTER adapter;
ListView YOUR_LISTVIEW;
ArrayList<YOUR_DATA_TYPE> listViewData;
onCreate(...){
.....
.....
//ListView data Initialization
listViewData = new ArrayList<YOUR_DATA_TYPE>();
listViewData.clear();
YOUR_LISTVIEW = (ListView)findViewById(R.id.YOUR_LISTVIEW_ID);
//adapter Initialization
adapter = new YOUR_CUSTOM_LISTVIEW_ADAPTER(....);
YOUR_LISTVIEW.setAdapter(adapter);
}
private OnScrollListener onScrollListener = new OnScrollListener() {
private int previousFirstVisibleItem = 0;
private long previousEventTime = 0;
private double speed = 0;
@Override
public void onScroll(HtcAbsListView view, int firstVisibleItem, int visibleItemCount, int totalItemCount)
{
if (previousFirstVisibleItem != firstVisibleItem)
{
long currTime = System.currentTimeMillis();
long timeToScrollOneElement = currTime - previousEventTime;
speed = ((double)1/timeToScrollOneElement)*1000;
previousFirstVisibleItem = firstVisibleItem;
previousEventTime = currTime;
Log.d("DBG", "Speed: " +speed + " elements/second");
//Tell adapter to not load images if it has reached a specific speed
if(speed>YOUR_DESIRED_VALUE)
{
doNotLoadImagesInListView();
}
else
{
loadImagesInListView();
}
}
}
@Override
public void onScrollStateChanged(HtcAbsListView view, int scrollState)
{
}
};
void doNotLoadImagesInListView()
{
adapter.isScrollFast = true;
adapter.notifyDataSetChanged();
YOUR_LISTVIEW.setAdapter(adapter);
}
void loadImagesInListView()
{
adapter.isScrollFast = false;
adapter.notifyDataSetChanged();
YOUR_LISTVIEW.setAdapter(adapter);
}
}
配置您的自定义列表适配器以进行相应的更改:
public class yourCustomAdapter extends BaseAdapter
{
public Boolean isScrollFast;
public yourCustomAdapter(..... , ....., Boolean isScrollFast)
{
....
this.isScrollFast = isScrollFast;
.....
}
@Override
public int getCount()
{
.....
}
@Override
public Object getItem(int position)
{
.....
}
@Override
public long getItemId(int position)
{
.....
}
@Override
public View getView(int position, View convertView, ViewGroup parent)
{
.......
if(isScrollFast==true)
{
//Don't Load Images
}
else
{
//Load Images normally
}
return vi;
}
}
我希望这适合你。