初学 WebView

WebViewallows you to create your own window for viewing web pages (or even develop a complete browser). In this tutorial, you'll create a simpleActivitythat can view and navigate web pages.


  1. Create a new project namedHelloWebView.
  2. Open theres/layout/main.xmlfile and insert the following:
    <?xml version="1.0" encoding="utf-8"?>
    <WebView  xmlns:android="http://schemas.android.com/apk/res/android"
        android:id="@+id/webview"
        android:layout_width="fill_parent"
        android:layout_height="fill_parent"
    />
  3. Now open theHelloWebView.javafile. At the top of the class, declare aWebViewobject:
    WebView mWebView;

    Then use the following code for theonCreate()method:

    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.main);
    
        mWebView = (WebView) findViewById(R.id.webview);
        mWebView.getSettings().setJavaScriptEnabled(true);
        mWebView.loadUrl("http://www.baidu.com");
    }

    This initializes the memberWebViewwith the one from theActivitylayout; requests aWebSettingsobject withgetSettings(); and enables JavaScript for theWebViewwithsetJavaScriptEnabled(boolean). Finally, an initial web page is loaded withloadUrl(String).

  4. Because this application needs access to the Internet, you need to add the appropriate permissions to the Android manifest file. Open theAndroidManifest.xmlfile and add the following as a child of the<manifest>element:
    <uses-permission android:name="android.permission.INTERNET" />
  5. While you're in the manifest, give some more space for web pages by removing the title bar, with the "NoTitleBar" theme:
    <activity android:name="你自己的activity name" android:label="@string/app_name"
      android:theme="@android:style/Theme.NoTitleBar">
  6. Now run the application.

    You now have a simplest web page viewer. It's not quite a browser yet because as soon as you click a link, the default Android Browser handles the Intent to view a web page, because thisActivityisn't technically enabled to do so. Instead of adding an intent filter to view web pages, you can override theWebViewClientclass and enable thisActivityto handle its own URL requests.

  7. In theHelloAndroidActivity, add this nested class:
    private class HelloWebViewClient extends WebViewClient {
        @Override
        public boolean shouldOverrideUrlLoading(WebView view, String url) {
            view.loadUrl(url);
            return true;
        }
    }
  8. Then towards the end of theonCreate(Bundle)method, set an instance of theHelloWebViewClientas theWebViewClient:
    mWebView.setWebViewClient(new HelloWebViewClient());

    This line can go anywhere following the initialization of theWebViewobject.

    This creates aWebViewClientthat will load any URL selected from thisWebViewinto the sameWebView. TheshouldOverrideUrlLoading(WebView, String)method is passed the currentWebViewand the URL requested, so all it needs to do is load the URL in the given view. Returningtruesays that the method has handled the URL and the event should not propagate (in which case, an Intent would be created that's handled by the Browser application).

    If you run the application again, new pages will now load in this Activity. However, you can't navigate back to previous pages. To do this, you need to handle the BACK button on the device, so that it will return to the previous page, rather than exit the application.

  9. To handle the BACK button key press, add the following method inside theHelloWebViewActivity:
    @Override
    public boolean onKeyDown(int keyCode, KeyEvent event) {
        if ((keyCode == KeyEvent.KEYCODE_BACK) && mWebView.canGoBack()) {
            mWebView.goBack();
            return true;
        }
        return super.onKeyDown(keyCode, event);
    }

    ThisonKeyDown(int, KeyEvent)callback method will be called anytime a button is pressed while in the Activity. The condition inside uses theKeyEventto check whether the key pressed is the BACK button and whether theWebViewis actually capable of navigating back (if it has a history). If both are true, then thegoBack()method is called, which will navigate back one step in theWebViewhistory.Returningtrueindicates that the event has been handled. If this condition is not met, then the event is sent back to the system.

  10. Run the application again. You'll now be able to follow links and navigate back through the page history.

When you open the application, it should look like this:


  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值