`
zhangziyangup
  • 浏览: 1081376 次
文章分类
社区版块
存档分类
最新评论

WebView显示网页

 
阅读更多

android.webkit.WebView是使用WebKit技术的View,主要的用途是显示网页。通过WebView,我们可以在Android应用程序中显示HTML文件或在线网页。


实现方法:

建立一个android工程,编辑.java文件:

package com.android;

import android.app.Activity;
import android.os.Bundle;
import android.webkit.WebView;

public class WebTestActivity extends Activity {
    /** Called when the activity is first created. */
    @Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.main);
        
        final String mimetype = "text/html";
        final String encoding = "utf-8";
        
        WebView wv;
        
        wv = (WebView) findViewById(R.id.wv);
        wv.loadData("<a href ='http://blog.csdn.net/imyang2007?viewmode=contents'>Young's Blog</a>", mimetype, encoding); 
 }
}
用XML layout来对UI布局,编辑main.XML:
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
    android:layout_width="fill_parent"
    android:layout_height="fill_parent"
    android:orientation="vertical" >

    <TextView
        android:layout_width="fill_parent"
        android:layout_height="wrap_content"
        android:text="@string/hello" />
    <WebView 
	android:layout_width="fill_parent" 
	android:layout_height="wrap_content" 
	android:id="@+id/wv" 
	/>
    

</LinearLayout>

在这里定义了一个WebView标签,并把该标签的id命名为wv,通过指定ID属性给View的方式,让应用程序在运行时期(run-time)找到相应的view对象。在就是findViewById在代码中的作用,在我们编辑main.XML文件后,R.java文件也会对应更新,我们可以看见在R.java中,多了一个:
    public static final class id {
        public static final int wv=0x7f050000;
    }

  1. 取得WebVeiw对象后,调用WebView.loadData方法,将HTML内容载入到webview,并显示在Activity上。loadData参数:
    • HTML内容
    • MimeType类型,指定为text/html,即为HTML文件
    • 文字编码方式,utf-8,Unicode方式。
效果图:

点击后:


分享到:
评论

相关推荐

Global site tag (gtag.js) - Google Analytics