How do I know that the scrollview is already scrolled to the bottom?
I have a scrollview and I only want an event to happen if it's already scrolled to the bottom but I can't find a way to check if the scrollview is at the bottom.
I have solved it for the opposite; only allow the event to happen if it's already scrolled to the top:
ScrollView sv = (ScrollView) findViewById(R.id.Scroll);
if(sv.开发者_开发知识库getScrollY() == 0) {
//do something
}
else {
//do nothing
}
I found a way to make it work. I needed to check the measured height of the child to the ScrollView, in this case a LinearLayout. I use the <= because it also should do something when scrolling isn't necessary. I.e. when the LinearLayout is not as high as the ScrollView. In those cases getScrollY is always 0.
ScrollView scrollView = (ScrollView) findViewById(R.id.ScrollView);
LinearLayout linearLayout = (LinearLayout) findViewById(R.id.LinearLayout);
if(linearLayout.getMeasuredHeight() <= scrollView.getScrollY() +
scrollView.getHeight()) {
//do something
}
else {
//do nothing
}
Here it is:
public class myScrollView extends ScrollView
{
public myScrollView(Context context)
{
super(context);
}
public myScrollView(Context context, AttributeSet attributeSet)
{
super(context,attributeSet);
}
@Override
protected void onScrollChanged(int l, int t, int oldl, int oldt)
{
View view = (View)getChildAt(getChildCount()-1);
int d = view.getBottom();
d -= (getHeight()+getScrollY());
if(d==0)
{
//you are at the end of the list in scrollview
//do what you wanna do here
}
else
super.onScrollChanged(l,t,oldl,oldt);
}
}
You can either use myScrollView in xml layout or instantiate it in your code. Hint: with code above if user hits the end of the list 10 times frequently then your code will run 10 times. In some cases like when you want to load data from a remote server to update your list, that behavior would be undesired (most probably). try to predict undesired situation and avoid them.
Hint 2: sometimes getting close to the end of the list may be the right time to let your script run. for example user is reading a list of articles and is getting close to the end. then you start loading more before list finishes. To do so, just do this to fulfill your purpose:
if(d<=SOME_THRESHOLD) {}
You can get the maximum scroll for the width by doing this
int maxScroll = yourScrollView.getChildAt(0).getMeasuredWidth() - yourScrollView.getWidth();
change getWidth() to getHeight() for vertical scroll views
If scrollView.getHeight() == scrollView.getScrollY + screensize, then it is scrolled to bottom.
精彩评论