關于WebView,一般涉及到2個類:WebChromeClient 和 WebViewClient 。
開發的大致流程為(摘自Android developer):
A WebView has several customization points where you can add your own behavior. These are:
Creating and setting a WebChromeClient subclass. This class is called when something that might impact a browser UI happens, for instance, progress updates and JavaScript alerts are sent here (see Debugging Tasks).
Creating and setting a WebViewClient subclass. It will be called when things happen that impact the rendering of the content, eg, errors or form submissions. You can also intercept URL loading here (via shouldOverrideUrlLoading()).
Modifying the WebSettings, such as enabling JavaScript with setJavaScriptEnabled().
Injecting Java objects into the WebView using the addJavascriptInterface(Object, String) method. This method allows you to inject Java objects into a page's JavaScript context, so that they can be accessed by JavaScript in the page.
好了,廢話不多說,上Demo。
此demo完成了Android與Javascript交互的基礎功能,并用json字符串進行了值傳遞。
秉持一貫的風格,知識內容都在代碼注釋中,這樣方便以后復習。(布局就不貼了,比較簡單)
整個工程結構比較簡單: