2014年2月27日星期四

[Android] How to detect if a listview is scrolling up or down

http://blog.evoxmusic.fr/content/android-how-detect-if-listview-scrolling-or-down

Hi there,
just a trick that I find on StackOverflow and adapt (to my case) for ListView instead of ScrollView.
It could be nice to know if you are scrolling up and down over a list to be notified and then do whatever you want.


Here I am gonna explain how to this easily..
There is a method in ListView ListView that reports the shifting of scrolls. It is called onScrollChanged(). However, it is declared protected, so you must create a wrapper class to gain access. For the usage of the method, please check android docs.
First, create an interface to expose the protected method

  1. public interface OnScrollListener {
  2.     void onScrollUpAndDownChanged(int x, int y, int oldx, int oldy);
  3. }
Then, create your wrapper and extend ListView.

  1. public class MyCustomListView extends ListView {
  2. private OnScrollListener onScrollListener = null;
  3.  
  4. public MyCustomListView(Context context) {
  5.     super(context);
  6. }
  7.  
  8. public MyCustomListView(Context context, AttributeSet attrs, int defStyle) {
  9.     super(context, attrs, defStyle);
  10. }
  11.  
  12. public MyCustomListView(Context context, AttributeSet attrs) {
  13.     super(context, attrs);
  14. }
  15.  
  16. public void setOnScrollUpAndDownListener(OnScrollListener onScrollListener) {
  17.     this.onScrollListener = onScrollListener;
  18. }
  19.  
  20. @Override
  21. protected void onScrollChanged(int x, int y, int oldx, int oldy) {
  22.     super.onScrollChanged(x, y, oldx, oldy);
  23.     if (onScrollListener != null) {
  24.         onScrollListener.onScrollUpAndDownChanged(x, y, oldx, oldy);
  25.     }
  26. }
  27. }
Finally, include it in your XML layout like a custom view, and attach listeners like usual.

  1. <your mycustomlistview />
  2.  
  3. myinstance.setOnScrollUpAndDownListener(new OnScrollListener() {...});
Hope this help you to enhance android possibilities like always :)
Cheers
My references: 
- See more at: http://blog.evoxmusic.fr/content/android-how-detect-if-listview-scrolling-or-down#sthash.iYEIREIZ.dpuf

没有评论:

发表评论