WebView是一个开放的浏览器组件,基于WebKit内核开发出来的,在Android系统中,默认提供给了我们WebView组件的支持,我们可以直接使用WebView组件显示网页的内容。
下面是一个简单的Demo,使用的是loadUrl()方法,要求在()中输入URL地址(如www.baidu.com),单击浏览后即可将指定的URL加载到WebView中。
首先是布局文件:
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout
xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:orientation="vertical">
<LinearLayout
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:orientation="horizontal">
<Button
android:id="@+id/open"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="打开"/>
<EditText
android:id="@+id/inputurl"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:text="http://"/>
</LinearLayout>
<WebView
android:id="@+id/webview"
android:layout_width="match_parent"
android:layout_height="match_parent"/>
</LinearLayout>
很简单的布局,没有需要特别说明的。
下面就是Activity程序:
package com.administrator.webview;
import android.app.Activity;
import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.view.View;
import android.webkit.WebView;
import android.widget.Button;
import android.widget.EditText;
public class MainActivity extends Activity {
private EditText inputurl;
private Button open;
private WebView mWebView;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
inputurl= (EditText) findViewById(R.id.inputurl);
open= (Button) findViewById(R.id.open);
mWebView= (WebView) findViewById(R.id.webview);
open.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
String url=inputurl.getText().toString();
mWebView.loadUrl(url);
}
});
}
}
在MainActivity.java中,使用loadUrl()方法,打开了一个页面。
效果如下:
非常简单的一个小Demo。