在做類似于淘寶寶貝詳情頁面時遇到問題,webview加載html文本內(nèi)的圖片布局不能自適應(yīng)屏幕大小
結(jié)局參考
https://stackoverflow.com/questions/10395292/android-webview-scaling-image-to-fit-the-screen
解決方法,按照回答設(shè)置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);
設(shè)置webview顯示高度自適應(yīng)內(nèi)容
@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)));
}
});
}