Android 内容使用浏览器WebView

activity_web_view.xml文件内容
<?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">
<WebView
    android:id="@+id/wv_1"
    android:layout_width="match_parent"
    android:layout_height="match_parent">
</WebView>
</LinearLayout>
后端核心代码
package com.example.testapp;

import androidx.annotation.RequiresApi;
import androidx.appcompat.app.AppCompatActivity;

import android.os.Build;
import android.os.Bundle;
import android.view.KeyEvent;
import android.webkit.WebResourceRequest;
import android.webkit.WebView;
import android.webkit.WebViewClient;

public class WebViewActivity extends AppCompatActivity {

    private WebView webView;
    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_web_view);
        webView=findViewById(R.id.wv_1);
        webView.getSettings().setJavaScriptEnabled(true);//使用javaScript
        webView.setWebViewClient(new MyWebViewClient());//使网页不会跳转到 手机浏览器
        webView.loadUrl("http://www.995w.com");
    }

    //按返回键 返回网页上一次浏览页面 功能
    @Override
    public boolean onKeyDown(int keyCode, KeyEvent event) {
        if(keyCode==KeyEvent.KEYCODE_BACK&&webView.canGoBack()){
            webView.goBack();
        }else {
            return super.onKeyDown(keyCode,event);
        }
        return true;
    }

    class MyWebViewClient extends WebViewClient {
        @RequiresApi(api = Build.VERSION_CODES.LOLLIPOP)
        @Override
        public boolean shouldOverrideUrlLoading(WebView view, WebResourceRequest request) {
            view.loadUrl(request.getUrl().toString());
            return true;
        }
    }
}

评论