问题
Im trying to use the webview's scroll position to determine whether SwipeRefreshLayout should be able to refresh, except for some websites e.g. https://jobs.lever.co/memebox, getScrollY() always returns 0. Is there a way to ensure I will always get the correct scroll position?
回答1:
The site you linked has a fixed header. My guess is that the page itself doesn't scroll; a container inside it does. The WebView can't inspect every scrollable container on the page, so it sees that the top-level container doesn't scroll and assumes that the entire thing is fixed.
If all you need this for is pull-to-refresh, I'd recommend adding a refresh button in addition to the SwipeRefreshLayout.
回答2:
Maybe you can try to add this to your custom webview
just tell it's scrolling
@Override
public boolean onTouchEvent(MotionEvent event) {
switch (event.getAction()){
case MotionEvent.ACTION_DOWN:
if(this.getScrollY() <= 0){
this.scrollTo(0,1);
}
break;
case MotionEvent.ACTION_UP:
break;
}
return super.onTouchEvent(event);
}
and then override onScrollChanged
@Override
protected void onScrollChanged(int l, int t, int oldl, int oldt) {
super.onScrollChanged(l, t, oldl, oldt);;
if (iWebViewScrollListener != null && t == 0) {
iWebViewScrollListener .onTop();
} else if (mIWebViewScroll != null && t != 0) {
iWebViewScrollListener .notOnTop();
}
}
add an top listener call back when scrolling.When is onTop() use setEnabled(true) for SwipeRefreshLayout,else setEnabled(false)
回答3:
Check your web layout. position: relative; in your CSS might be the source of your problem. Relative positioning causes troubles with scrolling in the WebView.
回答4:
This is a bit old but this problem still exists. For anyone wondering, I solved this by doing the following.
In GestureListener:
private class GestureListener extends GestureDetector.SimpleOnGestureListener {
@Override
public boolean onScroll(MotionEvent e1, MotionEvent e2, float distanceX, float distanceY) {
if(distanceY>0) webView.scrollBy(0,1);
else webView.scrollBy(0,-1);
}
}
Now it's possible to enable/disable the swipeRefreshLayout correctly using getScrollY as below:
swipeLayout.getViewTreeObserver().addOnGlobalLayoutListener(new ViewTreeObserver.OnGlobalLayoutListener() {
@Override
public void onGlobalLayout() {
ViewTreeObserver observer = swipeLayout.getViewTreeObserver();
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.JELLY_BEAN) {
observer.removeOnGlobalLayoutListener(this);
} else {
observer.removeGlobalOnLayoutListener(this);
}
observer.addOnScrollChangedListener(new ViewTreeObserver.OnScrollChangedListener() {
@Override
public void onScrollChanged() {
if (webView.getScrollY()==0) {
swipeLayout.setEnabled(true);
} else {
swipeLayout.setEnabled(false);
}
}
});
}
});
来源:https://stackoverflow.com/questions/29134082/webview-getscrolly-always-returns-0