android 检测ListView滚动到的位置
ListView滚动
1.要用到一个监听事件是:setOnScrollListener();
API解释是:
Set the listener that will receive notifications every time the list scrolls.
Parameters:l the scroll listener
- 2.它里面包含了两个方法:
- 一个是:onScrollStateChanged(AbsListView view, int scrollState),用来表明ListView是什么状态(静止,滑动);
- scrollState 为OnScrollListener.SCROLL_STATE_IDLE:表明ListView是在静止状态
- 为OnScrollListener.SCROLL_STATE_TOUCH_SCROLL:表明在滑动且手指没有离开屏幕.
- 另外一个是:onScroll(AbsListView view, int firstVisibleItem,int visibleItemCount, int totalItemCount)在滚动的时候获得一些参数:
- 通过一个小例子来说明:
1 public class MainActivity extends Activity { 2 private ListView listView; 3 4 @Override 5 protected void onCreate(Bundle savedInstanceState) { 6 super.onCreate(savedInstanceState); 7 setContentView(R.layout.activity_main); 8 listView = (ListView) findViewById(R.id.lsitView); 9 List<String> list = new ArrayList<String>(); 10 for (int i = 0; i < 20; i++) { 11 list.add("这是第" + i + "个"); 12 13 } 14 ArrayAdapter<String> adapter = new ArrayAdapter<String>(this, 15 android.R.layout.simple_list_item_single_choice, list); 16 listView.setAdapter(adapter); 17 listView.setOnScrollListener(new ListView.OnScrollListener() { 18 19 @Override 20 public void onScrollStateChanged(AbsListView view, int scrollState) { 21 switch (scrollState) { 22 23 case OnScrollListener.SCROLL_STATE_IDLE: // 没有滚动的时候 24 System.out.println("最后显示的listview的位置是--->>" 25 + listView.getLastVisiblePosition()); 26 if (listView.getLastVisiblePosition() == (listView 27 .getCount() - 1)) { 28 Toast.makeText(MainActivity.this, "滑到listView底了", 29 Toast.LENGTH_SHORT).show(); 30 31 } 32 33 if (listView.getFirstVisiblePosition() == 0) { 34 Toast.makeText(MainActivity.this, "listView顶头了", 35 Toast.LENGTH_SHORT).show(); 36 } 37 38 break; 39 40 case OnScrollListener.SCROLL_STATE_FLING: 41 System.out.println("SCROLL_STATE_FLING"); 42 break; 43 44 case OnScrollListener.SCROLL_STATE_TOUCH_SCROLL: 45 System.out.println("SCROLL_STATE_TOUCH_SCROLL" 46 + "能看到的最后一个显示的位置--->>" 47 + listView.getLastVisiblePosition()); 48 break; 49 default: 50 51 break; 52 53 } 54 55 } 56 57 /** 58 * view The view whose scroll state is being reported 59 * firstVisibleItem the index of the first visible cell (ignore if 60 * visibleItemCount == 0) visibleItemCount the number of visible 61 * cells totalItemCount the number of items in the list adaptor 62 */ 63 @Override 64 public void onScroll(AbsListView view, int firstVisibleItem, 65 int visibleItemCount, int totalItemCount) { 66 67 } 68 }); 69 70 } 71 }
源码下载地址:
源码
郑重声明:本站内容如果来自互联网及其他传播媒体,其版权均属原媒体及文章作者所有。转载目的在于传递更多信息及用于网络分享,并不代表本站赞同其观点和对其真实性负责,也不构成任何其他建议。