1.加载H5提示ERR_CLEARTEXT_NOT_PERMITTED
解决方案:在manifest的application中添加android:usesCleartextTraffic="true"
<?xml version="1.0" encoding="utf-8"?>
<manifest ...>
<uses-permission android:name="android.permission.INTERNET" />
<application
...
android:usesCleartextTraffic="true"
...>
...
</application>
</manifest>
2.内容宽度获取适配
import android.app.Activity;
import android.os.Bundle;
import android.support.v7.app.AppCompatActivity;
import android.util.Log;
import android.webkit.JavascriptInterface;
import android.webkit.WebSettings;
import android.webkit.WebView;
import android.webkit.WebViewClient;
public class Main extends AppCompatActivity {
private final Activity activity = this;
private WebView webView;
private int contentWidth = 0;
@Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
webView = (WebView) findViewById(R.id.webview);
WebSettings ws = webView.getSettings();
// 网页内容的宽度是否可大于WebView控件的宽度
ws.setLoadWithOverviewMode(false);
// 设置此属性,可任意比例缩放。
ws.setUseWideViewPort(true);
// 不缩放
// webView.setInitialScale(100);
// 告诉WebView启用JavaScript执行。默认的是false。
ws.setJavaScriptEnabled(true);
webView.addJavascriptInterface(new JavaScriptInterface(), "HTMLOUT");
webView.setWebViewClient(new WebViewClient() {
@Override
public void onPageFinished(WebView view, String url) {
if (contentWidth == 0) {
webView.loadUrl("javascript:window.HTMLOUT.getContentWidth(document.getElementsByTagName('html')[0].scrollWidth);");
}
}
});
webView.loadUrl("http://file.aimymusic.com/privacyClause.html");
}
class JavaScriptInterface {
@JavascriptInterface
public void getContentWidth(String value) {
if (value != null) {
contentWidth = Integer.parseInt(value);
final float size = activity.getResources().getDisplayMetrics().widthPixels * 100f / contentWidth;
Log.e("CASE", "size=" + size);
runOnUiThread(new Runnable() {
@Override
public void run() {
webView.setInitialScale((int) size);//可能会出现从大字体变为小字体的闪一下效果,可以重新调用初始化,设置setInitialScale后重新加载
}
});
}
}
}
}
网友评论