Android之WebView加载网页

来源:互联网 发布:开眼角疤痕知乎 编辑:程序博客网 时间:2024/05/21 05:20

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 stubView 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(){@Overridepublic boolean shouldOverrideUrlLoading(WebView view, String url) {// 返回值是true的时候控制去WebView打开,为false调用系统浏览器或第三方浏览器view.loadUrl(url);return true;}@Overridepublic void onPageStarted(WebView view, String url, Bitmap favicon) {//正在加载super.onPageStarted(view, url, favicon);}@Overridepublic void onPageFinished(WebView view, String url) {//加载完成super.onPageFinished(view, url);}});return view;}@Overrideprotected 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() {@Overridepublic void onClick(View v) {// TODO Auto-generated method stubsetWebView(inflater);}});}}



0 0
原创粉丝点击