Android 之 WebView 组件

来源:互联网 发布:js 删除一个tr 编辑:程序博客网 时间:2024/05/17 04:50

WebView是一个使用 WebKit 引擎的浏览器组件, 

可以将WebView 当成一个完整的浏览器使用,它不仅支持HTML、CSS等静态元素,还支持JavaScript,可以在JS中调用Java 的方法

WebView 组件不仅可以浏览网页,还可以浏览保存在本地的网页文件或WebView 支持的文件,

还可以缓存浏览历史页面,向后或向前浏览页面:


webView.goBack();             //  向后浏览历史页面

webView.goForward();       //   向前浏览历史页面

webView.clearCache();     //    要清除缓存内容 

下面一个示例程序: 将英文词典整合到 Web 页中(JavaScript 调用 Java方法)

主要代码:

public class Main extends Activity { // 定义ContentProvider 提供者 public final String DICTIONARY_SINGLE_WORD_URI =    "content://net.blogjava.mobile.dictionarycontentprovider/single"; @Override public void onCreate(Bundle savedInstanceState) {  super.onCreate(savedInstanceState);  setContentView(R.layout.main);  WebView webView = (WebView) findViewById(R.id.webview);  WebSettings webSettings = webView.getSettings();  webSettings.setJavaScriptEnabled(true);  webView.setWebChromeClient(new WebChromeClient());    webView.addJavascriptInterface(new Object()  {   //<span style="font-size:32px;color:#ff0000;"> 用于查询英文单词的方法,也是JavaScript调用的方法</span>   @SuppressWarnings("unused")   public  String searchWord(String word)   {    //直接通过 ContentProvider 来查询英文单词    Uri uri = Uri.parse(DICTIONARY_SINGLE_WORD_URI);    Cursor cursor = getContentResolver().query(uri, null,      "english=?", new String[]{ word }, null);    String result = "未找到该单词.";    if (cursor.getCount() > 0)  {     cursor.moveToFirst();     result = cursor.getString(cursor.getColumnIndex("chinese"));    }    return result;   }   //dictionary 是 Java 对象映射到JavaScript中的对象名  }, "dictionary");    // 开始读取res/raw 目录中的dictionary.html文件的内容  InputStream is = getResources().openRawResource(R.raw.dictionary);  byte[] buffer = new byte[1024];  try  {   int count = is.read(buffer);   String html = new String(buffer,0 ,count, "utf-8");   // 装载 dictionary.html 文件中的内容   webView.loadDataWithBaseURL(null, html, "text/html", "utf-8", null);  } catch (Exception e){} }}

dictionary.html 文件代码:

<html> <script language="javascript">    function search() {               result.innerHTML = "<font color='red'>" + window.dictionary.searchWord(word.value) + "</font>";    }</script><body>        英文词典<p/>           <input type="text" id="word"/> <input type="button" value="查单词" onclick="search()" />   <p/>   <div id="result"></div>    </body></html>

具体代码请参见 

ch09_webdictionary,  ch06_dictionary_contentprovider

(数据提供者)工程,界面效果


原创粉丝点击