温馨提示×

android webview如何加载网页

小樊
82
2024-09-03 01:06:00
栏目: 编程语言

在Android中,要使用WebView加载网页,请按照以下步骤操作:

  1. 首先,确保在AndroidManifest.xml文件中添加了Internet权限:
<uses-permission android:name="android.permission.INTERNET" />
  1. 在布局文件(例如activity_main.xml)中添加WebView控件:
<?xml version="1.0" encoding="utf-8"?><LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:app="http://schemas.android.com/apk/res-auto"
    xmlns:tools="http://schemas.android.com/tools"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    android:orientation="vertical"
    tools:context=".MainActivity">

   <WebView
        android:id="@+id/webView"
        android:layout_width="match_parent"
        android:layout_height="match_parent"/>

</LinearLayout>
  1. 在Activity(例如MainActivity.java)中,初始化并配置WebView:
import androidx.appcompat.app.AppCompatActivity;
import android.os.Bundle;
import android.webkit.WebSettings;
import android.webkit.WebView;
import android.webkit.WebViewClient;

public class MainActivity extends AppCompatActivity {

    private WebView webView;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);

        webView = findViewById(R.id.webView);
        webView.setWebViewClient(new WebViewClient());
        WebSettings webSettings = webView.getSettings();
        webSettings.setJavaScriptEnabled(true);
        
        // 加载网页
        webView.loadUrl("https://www.example.com");
    }

    @Override
    public void onBackPressed() {
        if (webView.canGoBack()) {
            webView.goBack();
        } else {
            super.onBackPressed();
        }
    }
}

这段代码会让WebView加载指定的网址(在本例中为 “https://www.example.com”)。同时,通过重写 onBackPressed() 方法,可以实现返回上一个页面的功能。

0