安卓无尽列表 [英] Android Endless List
问题描述
如何创建一个列表,当您到达列表末尾时,我会收到通知,以便我可以加载更多项目?
How can I create a list where when you reach the end of the list I am notified so I can load more items?
推荐答案
一种解决方案是实现一个 OnScrollListener
并对 ListAdapter
在其 onScroll
方法中处于方便的状态.
One solution is to implement an OnScrollListener
and make changes (like adding items, etc.) to the ListAdapter
at a convenient state in its onScroll
method.
下面的 ListActivity
显示了一个整数列表,从 40 开始,当用户滚动到列表末尾时添加项目.
The following ListActivity
shows a list of integers, starting with 40, adding items when the user scrolls to the end of the list.
public class Test extends ListActivity implements OnScrollListener {
Aleph0 adapter = new Aleph0();
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setListAdapter(adapter);
getListView().setOnScrollListener(this);
}
public void onScroll(AbsListView view,
int firstVisible, int visibleCount, int totalCount) {
boolean loadMore = /* maybe add a padding */
firstVisible + visibleCount >= totalCount;
if(loadMore) {
adapter.count += visibleCount; // or any other amount
adapter.notifyDataSetChanged();
}
}
public void onScrollStateChanged(AbsListView v, int s) { }
class Aleph0 extends BaseAdapter {
int count = 40; /* starting amount */
public int getCount() { return count; }
public Object getItem(int pos) { return pos; }
public long getItemId(int pos) { return pos; }
public View getView(int pos, View v, ViewGroup p) {
TextView view = new TextView(Test.this);
view.setText("entry " + pos);
return view;
}
}
}
对于长时间运行的操作(例如加载网络数据),您显然应该使用单独的线程,并且可能希望指示最后一个列表项的进度(例如市场或 gmail 应用程序所做的).
You should obviously use separate threads for long running actions (like loading web-data) and might want to indicate progress in the last list item (like the market or gmail apps do).
这篇关于安卓无尽列表的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!