Created
August 28, 2014 15:41
-
-
Save Sefford/78553f5eec6feb39fd97 to your computer and use it in GitHub Desktop.
ListView that knows how much has been scrolled downwards
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
public class ScrollAwareListView extends ListView { | |
/** | |
* Vertical offset listener | |
*/ | |
OnVerticalScrollOffsetListener offsetListener; | |
/** | |
* Maximum vertical size | |
*/ | |
int verticalRange = 0; | |
/** | |
* {@inheritDoc} | |
*/ | |
public ScrollAwareListView(Context context) { | |
super(context); | |
} | |
/** | |
* {@inheritDoc} | |
*/ | |
public ScrollAwareListView(Context context, AttributeSet attrs) { | |
super(context, attrs); | |
} | |
/** | |
* {@inheritDoc} | |
*/ | |
public ScrollAwareListView(Context context, AttributeSet attrs, int defStyle) { | |
super(context, attrs, defStyle); | |
} | |
@Override | |
protected int computeVerticalScrollOffset() { | |
final int result = super.computeVerticalScrollOffset(); | |
if (offsetListener != null) { | |
offsetListener.onScrollOffsetComputed(result, verticalRange, verticalRange == 0 ? 0 : ((float) result / verticalRange) * getHeight()); | |
} | |
return result; | |
} | |
@Override | |
protected int computeVerticalScrollRange() { | |
final int result = super.computeVerticalScrollRange(); | |
if (verticalRange != result) { | |
verticalRange = result; | |
} | |
return result; | |
} | |
/** | |
* Sets a new Vertical Scroll offset listener | |
* | |
* @param offsetListener OffsetListener instance for listening | |
*/ | |
public void setOffsetListener(OnVerticalScrollOffsetListener offsetListener) { | |
this.offsetListener = offsetListener; | |
} | |
/** | |
* This interface will allow a class to listen for changes on the current offset of the | |
* Y-scroll of the list. Take into account that the changes in the size of the scroll | |
* are not constantly updated, however the offset will be | |
*/ | |
public interface OnVerticalScrollOffsetListener { | |
/** | |
* Receives the Current offset of the ListView | |
* | |
* @param currentOffset Current offset of the Y-scroll | |
* @param totalOffset Total offset of the Y-scroll | |
* @param percentage Percentage of the available offset of the Y-scroll moved. | |
*/ | |
void onScrollOffsetComputed(int currentOffset, int totalOffset, float percentage); | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment