Webview妙用(實現源生複雜UI頁面)
阿新 • • 發佈:2019-01-07
前幾天,前同事找到我,具體是讓我幫忙,實現一個類似答題的UI頁面(這哥們又接外包了--!)。
1、具體功能如圖:
2、做為一個android程式設計師,首先自然想到是在android上如何實現。捋了一下官方給出的所有控制元件,並沒有能解決該UI介面的方法,於是,只能自定義view了。
3、首先思路是建立自定義view,然後用textPaint繪製文字及下劃線。用onTouch判斷位置,設定點選事件。思路很清晰,做下去後發現,存在兩個問題。
- textPaint無法繪製出下劃線。(原因未明)
- 點選事件該如何設定。
4、無法繪製下劃線的問題,可能是廠商或者版本的問題,具體也沒有去深究了(真不是一個合格的程式設計師。。。)
5、既然解決不了上述兩個問題,只能用其他辦法了。條條大路同羅馬嘛,不能在一個衚衕裡面扎死。所以靈機一動,為什麼不用h5實現。
6、思路是有了,技術上基本沒有難點。點選事件只需要簡單的h5與源生互動。行了,馬上行動。
7、具體方法如下:
1、編寫h5程式碼:
/******************** * 作者:malus * 日期:16/10/15 * 時間:上午10:06 * 註釋: ********************/ public class StringUtil { static String[] str = {" ① "," ② "," ③ "," ④ "," ⑤ "," ⑥ "," ⑦ "," ⑧ "," ⑨ "," ⑩ "," ⑪ "," ⑫ "," ⑬ "," ⑭ "," ⑮ "," ⑯ "," ⑰ "," ⑱ "," ⑲ "," ⑳ "}; static String msg = "The Zapata rail (@ cerverai) is a medium-sized, dark-coloured rail. It has brown @, greyish-blue underparts, a red-based yellow bill, white undertail coverts, and red eyes and @. Its short wings render it almost flightless. It is endemic to the wetlands of the Zapata Peninsula in southern @, where its only known nest was found in sawgras."; static int mIndex = 0; public static String getQuestion(){ msg = "<!DOCTYPE html><meta http-equiv=\"Content-Type\" content=\"text/html; charset=utf-8\" /><html><body>"+msg+"</html></body>"; while (msg.contains("@")){ msg = msg.replaceFirst("@","<a href='http://www.baidu.com?index="+mIndex+"'>"+str[mIndex]+"</a>"); mIndex++; } return msg; } }
2、webview展示:
<span style="white-space:pre"> </span>mWebView = (WebView)findViewById(R.id.webview);
mWebView.loadData(StringUtil.getQuestion(),"text/html; charset=UTF-8",null);
3、點選事件互動:
<span style="white-space:pre"> </span>mWebView.setWebViewClient(new WebViewClient(){ @Override public void onLoadResource(WebView view, String url) { super.onLoadResource(view, url); } @Override public boolean shouldOverrideUrlLoading(WebView view, String url) { if(url.contains("index=")){ String index = url.split("index=")[1]; int mIndex = Integer.parseInt(index); Toast.makeText(MainActivity.this,"答案"+mIndex,Toast.LENGTH_LONG).show(); } return true; } });
8、實現結果我就不描述了。這裡並沒有涉及到太難的技術點。我只是想提供一個思路,就是一個複雜的,源生難以實現的頁面,換做h5實現可能也是一個不錯的方法。如果只是簡單的loaddata,對效能的影響應該不大。
9、感謝閱讀,純分享,不喜勿噴。