首先我这里写的太少太少建议参考文档
https://www.apiref.com/android-zh/android/webkit/WebView.html
public class MainActivity extends AppCompatActivity {
private WebView WV;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
WV = findViewById(R.id.WV);
// 加载本地src/main/assets目录下HiHrk.html文件
// WV.loadUrl("file:///android_asset/HiHrk.html");
// 给予JavaScript权限
WV.getSettings().setJavaScriptEnabled(true);
// 添加WebViewClient
// WebViewClient用于设置接收各种通知和请求
WV.setWebViewClient(new WebViewClient() {
// 重写下面方法以实现打开多页面(不弹出使用浏览器打开)
@RequiresApi(api = Build.VERSION_CODES.LOLLIPOP)
@Override
public boolean shouldOverrideUrlLoading(WebView view, WebResourceRequest request) {
view.loadUrl(request.getUrl().toString());
return super.shouldOverrideUrlLoading(view, request);
}
});
// 添加WebChromeClient
// WebChromeClient用以提供您自己的行为以打开多个窗口,并以任何您想要的方式渲染它们。
WV.setWebChromeClient(new WebChromeClient(){
// 设置加载进度条
// newProgress是进度0-100
@Override
public void onProgressChanged(WebView view, int newProgress) {
super.onProgressChanged(view, newProgress);
if(newProgress==100)
Toast.makeText(view.getContext(),"加载完了",Toast.LENGTH_SHORT).show();
}
// 设置网页的title为activity的title
@Override
public void onReceivedTitle(WebView view, String title) {
super.onReceivedTitle(view, title);
setTitle(title);
}
});
WV.loadUrl("https://www.baidu.com");
}
// 添加按返回键的判断
@Override
public boolean onKeyDown(int keyCode, KeyEvent event) {
if (keyCode == KeyEvent.KEYCODE_BACK && WV.canGoBack()) {
WV.goBack();
return true;
}
return super.onKeyDown(keyCode, event);
}
}