在做类似于淘宝宝贝详情页面时遇到问题,webview加载html文本内的图片布局不能自适应屏幕大小
结局参考
https://stackoverflow.com/questions/10395292/android-webview-scaling-image-to-fit-the-screen
解决方法,按照回答设置webview显示方式
WebView content = (WebView) findViewById(R.id.webView1);
content.loadDataWithBaseURL(null, "<style>img{display: inline;height: auto;max-width: 100%;}</style>" + post.getContent(), "text/html", "UTF-8", null);
设置webview显示高度自适应内容
@SuppressLint("JavascriptInterface")
private void setupWebView() {
webview.getSettings().setJavaScriptEnabled(true);
webview.setWebViewClient(new WebViewClient() {
@Override
public void onPageFinished(WebView view, String url) {
webview.loadUrl("javascript:MyApp.resize(document.body.getBoundingClientRect().height)");
super.onPageFinished(view, url);
}
});
webview.addJavascriptInterface(this, "MyApp");
}
@JavascriptInterface
public void resize(final float height) {
MaterialDetailActivity.this.runOnUiThread(new Runnable() {
@Override
public void run() {
webview.setLayoutParams(new LinearLayout.LayoutParams(getResources().getDisplayMetrics().widthPixels, (int) (height * getResources().getDisplayMetrics().density)));
}
});
}