activity_main
<?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/webView"
android:layout_width="match_parent"
android:layout_height="match_parent" />
</LinearLayout>
MainActivity
import android.app.Activity;
import android.graphics.Bitmap;
import android.os.Bundle;
import android.text.TextUtils;
import android.webkit.WebView;
import android.webkit.WebViewClient;
public class MainActivity extends Activity {
private WebView mWebView;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
init();
}
private void init(){
mWebView= (WebView) findViewById(R.id.webView);
mWebView.setWebViewClient(new WebViewClient() {
@Override
public boolean shouldOverrideUrlLoading(WebView view, String url) {
if(!TextUtils.isEmpty(url)){
mWebView.loadUrl(url);
}
return super.shouldOverrideUrlLoading(view, url);
}
@Override
public void onReceivedError(WebView view, int errorCode, String description, String failingUrl) {
}
@Override
public void onPageStarted(WebView view, String url, Bitmap favicon) {
super.onPageStarted(view, url, favicon);
}
@Override
public void onPageFinished(WebView view, String url) {
super.onPageFinished(view, url);
}
});
mWebView.loadUrl("http://www.ifeng.com/");
}
@Override
protected void onPause() {
super.onPause();
mWebView.onPause();
}
@Override
protected void onResume() {
super.onResume();
mWebView.onResume();
}
@Override
protected void onDestroy() {
super.onDestroy();
mWebView.stopLoading();
}
@Override
public void onBackPressed() {
if (mWebView.canGoBack()){
mWebView.goBack();
}else {
super.onBackPressed();
}
}
}
AndroidManifest.xml
<?xml version="1.0" encoding="utf-8"?>
<manifest xmlns:android="http://schemas.android.com/apk/res/android"
package="com.etime.myproject">
<!-- 网络权限 -->
<uses-permission android:name="android.permission.INTERNET"/>
<!-- 使用明文网络流量 -->
<!-- android:usesCleartextTraffic="true" -->
<application
android:usesCleartextTraffic="true"
android:allowBackup="true"
android:icon="@mipmap/ic_launcher"
android:label="@string/app_name"
android:roundIcon="@mipmap/ic_launcher_round"
android:supportsRtl="true"
android:theme="@style/AppTheme">
<activity android:name=".MainActivity">
<intent-filter>
<action android:name="android.intent.action.MAIN" />
<category android:name="android.intent.category.LAUNCHER" />
</intent-filter>
</activity>
</application>
</manifest>
<uses-permission android:name="android.permission.INTERNET"/>
android:usesCleartextTraffic="true"