基本视图——WebView

作者:追风剑情 发布于:2015-9-29 20:27 分类:Android

一、配置AndroidManifest.xml权限

  1. <uses-permission android:name="android.permission.INTERNET" />

二、创建活动

视图

  1. <LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
  2. xmlns:tools="http://schemas.android.com/tools"
  3. android:layout_width="fill_parent"
  4. android:layout_height="fill_parent"
  5. android:orientation="vertical"
  6. tools:context="${relativePackage}.${activityClass}" >
  7.  
  8. <WebView
  9. android:id="@+id/webview1"
  10. android:layout_width="wrap_content"
  11. android:layout_height="wrap_content" />
  12.  
  13. </LinearLayout>

代码

  1. package com.example.androidtest;
  2.  
  3. import android.app.Activity;
  4. import android.os.Bundle;
  5. import android.webkit.WebSettings;
  6. import android.webkit.WebView;
  7. import android.webkit.WebViewClient;
  8.  
  9. public class WebViewActivity extends Activity {
  10.  
  11. @Override
  12. protected void onCreate(Bundle savedInstanceState) {
  13. super.onCreate(savedInstanceState);
  14. setContentView(R.layout.activity_web_view);
  15. WebView wv = (WebView) findViewById(R.id.webview1);
  16. WebSettings webSettings = wv.getSettings();
  17. webSettings.setBuiltInZoomControls(true);//显示内置放缩控件
  18. wv.setWebViewClient(new Callback());
  19. wv.loadUrl("http://www.baidu.com");
  20. //直接显示html字符串
  21. /*
  22. final String mimeType = "text/html";
  23. final String encoding = "UTF-8";
  24. String html = "<H1>A simple HTML page</H1><body>"+
  25. "<p>The quick brown fox jumps over the lazy dog</p>"+
  26. "</body>";
  27. wv.loadDataWithBaseURL("", html, mimeType, encoding, "");*/
  28. //直接加载assets文件夹下的html文件
  29. //wv.loadUrl("file:///xxxx/Index.html");
  30. }
  31. /**
  32. * 有时,当加载一个会重定向的页面时,WebView将导致应用程序启动设备的Browser
  33. * 应用程序来加载所需的页面。为了避免这种情况发生,需要实现WebViewClient类
  34. * 并重写shouldOverrideUrlLoading()方法。
  35. */
  36. private class Callback extends WebViewClient {
  37. @Override
  38. public boolean shouldOverrideUrlLoading (WebView view, String url)
  39. {
  40. return false;
  41. }
  42. }
  43. }

运行效果

webview.pngwebview1.png

标签: Android

Powered by emlog  蜀ICP备18021003号-1   sitemap

川公网安备 51019002001593号