1.主xml
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:tools="http://schemas.android.com/tools"
android:layout_width="match_parent"
android:layout_height="match_parent"
tools:context="com.fn.Web.MainActivity" >
<Button
android:id="@+id/baidu_btn"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="打开百度"/>
<RelativeLayout
android:id="@+id/view"
android:layout_below="@+id/baidu_btn"
android:layout_width="match_parent"
android:layout_height="match_parent"
/>
</RelativeLayout>
2.加载网页的xml
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:tools="http://schemas.android.com/tools"
android:layout_width="match_parent"
android:layout_height="match_parent"
tools:context="com.fn.Web.MainActivity" >
<WebView
android:id="@+id/web_view"
android:layout_width="match_parent"
android:layout_height="match_parent"/>
</RelativeLayout>
3.activity详细代码
package com.fn.Web;
import android.annotation.SuppressLint;
import android.app.Activity;
import android.graphics.Bitmap;
import android.os.Bundle;
import android.view.LayoutInflater;
import android.view.View;
import android.view.View.OnClickListener;
import android.webkit.WebView;
import android.webkit.WebViewClient;
import android.widget.Button;
import android.widget.RelativeLayout;
public class MainActivity extends Activity {
private LayoutInflater inflater = null;
private Button btn;
private RelativeLayout rl;
private WebView webView;
@SuppressLint("SetJavaScriptEnabled")
private View setWebView(LayoutInflater inflater) {
// TODO Auto-generated method stub
View view = inflater.inflate(R.layout.web_view, rl);
webView = (WebView) findViewById(R.id.web_view);
//访问的URL地址
webView.loadUrl("http://www.baidu.com");
//如果访问的页面中有Javascript,则webview必须设置支持Javascript。
webView.getSettings().setJavaScriptEnabled(true);
webView.setWebViewClient(new WebViewClient(){
@Override
public boolean shouldOverrideUrlLoading(WebView view, String url) {
// 返回值是true的时候控制去WebView打开,为false调用系统浏览器或第三方浏览器
view.loadUrl(url);
return true;
}
@Override
public void onPageStarted(WebView view, String url, Bitmap favicon) {
//正在加载
super.onPageStarted(view, url, favicon);
}
@Override
public void onPageFinished(WebView view, String url) {
//加载完成
super.onPageFinished(view, url);
}
});
return view;
}
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
inflater = LayoutInflater.from(this);
btn = (Button) findViewById(R.id.baidu_btn);
rl = (RelativeLayout) findViewById(R.id.view);
btn.setOnClickListener(new OnClickListener() {
@Override
public void onClick(View v) {
// TODO Auto-generated method stub
setWebView(inflater);
}
});
}
}
本文介绍了一个简单的 Android 应用示例,展示了如何使用 WebView 控件加载并显示网页内容。该应用包含一个按钮,点击后会加载百度首页。
1570

被折叠的 条评论
为什么被折叠?



