用一小塊webview顯示網(wǎng)頁(yè)里的二維碼信息

使用場(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)試。

?著作權(quán)歸作者所有,轉(zhuǎn)載或內(nèi)容合作請(qǐng)聯(lián)系作者
【社區(qū)內(nèi)容提示】社區(qū)部分內(nèi)容疑似由AI輔助生成,瀏覽時(shí)請(qǐng)結(jié)合常識(shí)與多方信息審慎甄別。
平臺(tái)聲明:文章內(nèi)容(如有圖片或視頻亦包括在內(nèi))由作者上傳并發(fā)布,文章內(nèi)容僅代表作者本人觀點(diǎn),簡(jiǎn)書(shū)系信息發(fā)布平臺(tái),僅提供信息存儲(chǔ)服務(wù)。

友情鏈接更多精彩內(nèi)容