最近有个需求webview滚动到顶部及底部触发一些操作,从网上找的例子都不太满意,主要有几点问题需要完善:
1.webview滚动到顶部或底部,应该是抬手后触发。
2.当H5内容高度小于webview本身设置的高度,页面不滚动,该如何触发顶部及底部动作。
最终效果
public class NestedWebView extends WebView {
//默认开始是顶部
boolean isScrolledToTop = true;
boolean isScrolledToBottom = false;
ScrollInterface mScrollInterface;
private int y = 0;
public NestedWebView(Context context) {
super(context);
}
public NestedWebView(Context context, AttributeSet attrs) {
super(context, attrs);
}
@Override
public boolean onTouchEvent(MotionEvent event) {
if(event.getAction() == MotionEvent.ACTION_DOWN){
y = (int) event.getY();
}
if (event.getAction() == MotionEvent.ACTION_UP) {
if(mScrollInterface != null){
Log.e("webScroll","y:"+event.getY());
int upTmp = y - (int)event.getY() ;
int downTmp = (int)event.getY() - y;
if (isScrolledToTop && downTmp > 10) {
// 触发滚动到顶部的事件
// 在这里添加你需要执行的逻辑
mScrollInterface.scrollTop();
} else if (isScrolledToBottom && upTmp > 10) {
// 触发滚动到底部的事件
// 在这里添加你需要执行的逻辑
mScrollInterface.scrollBottom();
}
}
}
return super.onTouchEvent(event);
}
public void initStatus(){
isScrolledToTop = true;
int contentHeight = (int) (this.getContentHeight() * this.getScale());
int webViewHeight = this.getHeight();
if(contentHeight <= webViewHeight){
isScrolledToBottom = true;
FrameLayout.LayoutParams ps = new FrameLayout.LayoutParams(FrameLayout.LayoutParams.MATCH_PARENT,FrameLayout.LayoutParams.MATCH_PARENT);
ps.rightMargin = SizeUtils.dpToPx(48);
this.setLayoutParams(ps);
}
}
@Override
protected void onScrollChanged(int l, int scrollY, int oldl, int oldt) {
super.onScrollChanged(l, scrollY, oldl, oldt);
int contentHeight = (int) (this.getContentHeight() * this.getScale());
int webViewHeight = this.getHeight();
if (scrollY == 0) {
isScrolledToTop = true;
isScrolledToBottom = false;
} else if (scrollY >= contentHeight - webViewHeight) {
isScrolledToTop = false;
isScrolledToBottom = true;
} else {
isScrolledToTop = false;
isScrolledToBottom = false;
}
}
public void setOnCustomScrollChangeListener(ScrollInterface mInterface) {
mScrollInterface = mInterface;
}
public interface ScrollInterface {
void scrollTop();
void scrollBottom();
}
}