WebView常見問題彙總以及解決方案
- 監聽WebView上下滑動
自定義WebView
import android.content.Context;
import android.util.AttributeSet;
import android.webkit.WebView;
/**
* 重新webview
*
* @author
*/
public class MyWebView extends WebView {
ScrollInterface web;
public MyWebView(Context context) {
super(context);
// TODO Auto-generated constructor stub
}
public MyWebView(Context context, AttributeSet attrs, int defStyle) {
super(context, attrs, defStyle);
}
public MyWebView(Context context, AttributeSet attrs) {
super(context, attrs);
// TODO Auto-generated constructor stub
}
@Override
protected void onScrollChanged(int l, int t, int oldl, int oldt) {
super.onScrollChanged(l, t, oldl, oldt);
//Log.e("hhah",""+l+" "+t+" "+oldl+" "+oldt);
web.onSChanged(l, t, oldl, oldt);
}
public void setOnCustomScroolChangeListener(ScrollInterface t) {
this.web = t;
}
/**
* 定義滑動接口
*
* @param
*/
public interface ScrollInterface {
public void onSChanged(int l, int t, int oldl, int oldt);
}
}
這裏定義了一個ScrollInterface 接口,其中l和t分別是Webview滾動後x和y方向上的座標,oldl, oldt分別是Webview滾動前的x和y方向上的座標。
現在一個對外提供了滾動參數的自定義webview就寫好了,讓我們看看如何在外部使用:
mWebView.setOnCustomScroolChangeListener(new MyWebView.ScrollInterface() {
@Override
public void onSChanged(int l, int t, int oldl, int oldt) {
//在這裏我們可以根據需求,實現功能,比如監聽滑動方向和是否滾動到底部
if (t - oldt > 0) {
//向下滑動要做的事情
} else if (t - oldt < 0) {
//向上滑動要做到事情
}
//WebView的總高度
float webViewContentHeight=mWebView.getContentHeight() * mWebView.getScale();
//WebView的現高度
float webViewCurrentHeight=(mWebView.getHeight() + mWebView.getScrollY());
if ((webViewContentHeight-webViewCurrentHeight) == 0) {
//滑動到底部
}
if (mWebView.getScrollY() == 0) {
//滑動到頂端
}
}
});
2 播放H5視頻的時候,黑屏,只有聲音沒有圖像
在AndroidManifest.xml中開啓硬件加速
AndroidManifest.xml
android:hardwareAccelerated="true"
同時,在webview中進行layerType設置
<WebView
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:layerType="hardware"
android:verticalScrollbarPosition="right"
android:scrollbars="vertical"
/>