本文选自StackOverflow(简称:SOF)精选问答汇总系列文章之一,本系列文章将为读者分享国外最优质的精彩问与答,供读者学习和了解国外最新技术。本文将讲解如何实现循环list。
当list滑动到底时,我怎样去操作,可以加载更多的item?
Josef Pfleger:(最佳方案)
一个解决方案是,执行OnScrollListener,用onScroll方法,在适当的环境中调整ListAdapter(例如,增加item)。
下面的ListActivity会从40开始,在用户滚动到list尾部时,显示整数list,
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
|
public Aleph0 new
protected super .onCreate(savedInstanceState); setListAdapter(adapter); getListView().setOnScrollListener( this ); } public int boolean /* firstVisible if (loadMore) adapter.count // adapter.notifyDataSetChanged(); } } public class int /* public return
public return
public return
public TextView new
this ); view.setText( "entry
return
} } } |
如果程序运转时间较长,最好使用单独线程。
我的这种方法是基于OnScrollListener界面,但这种方法在低端设备上的滚动效果更佳,因为在滚动操作中,计算出所有结果是难以执行的。
1. 让ListFragment或者ListActivity执行OnScrollListener
2. 在class上增加如下命令:
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
|
@Override public int //leave } @Override public if
if
currentPage++; //load loadElements(currentPage); } } } |
currentPage是应该加到list上的数据源,threshold是list item的数量(从尾部算起)。如果将threshold设置成0,用户不得不滚动到最后去加载更多item。
3.(可选)"load-more check"只会在用户停止滚动时才会弹出。为了使用方便,你可以在list末尾,使用listView.addFooterView(yourFooterView)增加一个陪在指示器。
举例如下:
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
|
<?xml "1.0"
"utf-8" ?> <RelativeLayout "http://schemas.android.com/apk/res/android" android:id= "@+id/footer_layout" android:layout_width= "fill_parent" android:layout_height= "wrap_content" android:padding= "10dp"
<ProgressBar android:id= "@+id/progressBar1" android:layout_width= "wrap_content" android:layout_height= "wrap_content" android:layout_centerVertical= "true" android:layout_gravity= "center_vertical"
<TextView android:layout_width= "wrap_content" android:layout_height= "wrap_content" android:layout_centerVertical= "true" android:layout_toRightOf= "@+id/progressBar1" android:padding= "5dp" android:text= "@string/loading_text"
</RelativeLayout> |
4.(可选)最后,如果通过item和page数量都没有增加的话,可以通过listView.removeFooterView(yourFooterView)重置配载指示器。
你可以凭借onScrollListener检测list末端,运行代码如下:
1
2
3
4
5
6
7
8
|
@Override public if
null
Log.v(TAG, "onListEnd, ); mPrevTotalItemCount mAdapter.addMoreData(); } } |
另一种方法是:
1
2
3
4
5
6
|
public if (pos==getCount()-1){ addMoreData(); //should } return
} |
使用这种方法,你还需要增加addMoreData()条件。
在list中加入所有元素后,你还需要调用适配器中notifyDataSetChanged() 来升级View。
文章选自StackOverFlow社区,鉴于其内容对于开发者有所帮助,现将文章翻译于此,供大家参考及学习。9Tech将每日持续更新,读者可点击StackOverflow(简称:SOF)精选问答汇总,查看全部译文内容。同时,我们也招募志同道合的技术朋友共同翻译,造福大家!报名请发邮件至zhangqi_wj@cyou-inc.com。
原文链接:http://stackoverflow.com/questions/1080811/android-endless-list