使用場(chǎng)景:當(dāng)你要在Activity或者Fragment顯示一塊網(wǎng)頁(yè)中的二維碼。因?yàn)槟撤N原因,你是獲得了這個(gè)網(wǎng)頁(yè)的URL,而不是二維碼的圖像
總的來(lái)說(shuō)我們需要在這么一塊webview上面顯示網(wǎng)頁(yè)里面的部分信息。
代碼
設(shè)置webview不能滑動(dòng)什么的,還有setJavaScriptEnabled(true)很關(guān)鍵
webView = view.findViewById(R.id.webview);
//設(shè)置滾動(dòng)條不顯示
webView.setHorizontalScrollBarEnabled(false);//水平不顯示
webView.setVerticalScrollBarEnabled(false); //垂直不顯示
// 使WebView不可滾動(dòng)
webView.setOnTouchListener((v, event) -> (event.getAction() == MotionEvent.ACTION_MOVE));
webView.getSettings().setJavaScriptEnabled(true);
關(guān)鍵代碼,在shouldInterceptRequest加載css樣式。
判斷url是否以css結(jié)尾,如果是,就用我們構(gòu)造的WebResourceResponse的來(lái)代替。
webView.setWebViewClient(new WebViewClient(){
@Nullable
@Override
public WebResourceResponse shouldInterceptRequest(WebView view, String url) {
Log.i(TAG,"shouldInterceptRequest "+url);
if(url.endsWith(".css")){
try {
return new WebResourceResponse("text/css","utf-8",getContext().getAssets().open("css/news.css"));
} catch (IOException e) {
e.printStackTrace();
}
}
return super.shouldInterceptRequest(view, url);
}
});
}
我們構(gòu)造的WebResourceResponse是加載了Assets下的css/news.css,實(shí)際上這個(gè)是我們自己創(chuàng)建的,簡(jiǎn)單而言就是讓網(wǎng)頁(yè)加載自己定義的css,從而達(dá)到自己想要的顯示效果。
看看css文件
body, html {
margin: 0;
padding: 0;
height: 100%;
}
body{width:135px;height:135px;
padding: 0px!important;
}
.impowerBox{
margin: 0;
padding: 0;
line-height: 0;
text-align: center;
position: relative;
width: 100%;
z-index: 1;
}
.impowerBox .qrcode {width: 135px; height:135px; }
.impowerBox .title {display: none;}
.impowerBox .info {display: none;}
.status_icon {display: none}
.impowerBox .status {display: none;}
我把一些不顯示的設(shè)置成display: none,然后固定了它的大小等,實(shí)現(xiàn)了自己想要的顯示效果。至于具體的效果,自己可以慢慢調(diào)試。