记得 要先给权限能够访问网络
在AndroidManifest.xml 中加入 <uses-permission android:name="android.permission.INTERNET"/> 就可以了
MainActivity.java
package com.example.webview;
import android.os.Bundle;
import android.app.Activity;
import android.view.Menu;
import android.view.View;
import android.webkit.WebSettings;
import android.webkit.WebView;
import android.webkit.WebViewClient;
import android.widget.Toast;
public class MainActivity extends Activity {
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
}
public void openweb(View v){
Toast.makeText(this, "正在进入网页", 0).show();
WebView webview = (WebView)findViewById(R.id.webview);
webview.loadUrl("https://www.baidu.com");
webview.setWebViewClient(new WebViewClient());
WebSettings websettings = webview.getSettings();
websettings.setJavaScriptEnabled(true);
websettings.setUseWideViewPort(true);
websettings.setLoadWithOverviewMode(true);
}
}
activity_main.xml
<LinearLayout 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"
android:orientation="vertical"
tools:context=".MainActivity" >
<Button
android:onClick="openweb"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:text="点击进入网页"
/>
<WebView
android:id="@+id/webview"
android:layout_width="match_parent"
android:layout_height="match_parent"
/>
</LinearLayout>