xml文件
<?xml version="1.0" encoding="utf-8"?>
<androidx.constraintlayout.widget.ConstraintLayout
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">
<WebView
android:id="@+id/webview"
android:layout_width="411dp"
android:layout_height="655dp"
android:layout_marginBottom="4dp"
app:layout_constraintBottom_toBottomOf="parent"
app:layout_constraintEnd_toEndOf="parent"
app:layout_constraintHorizontal_bias="0.4"
app:layout_constraintStart_toStartOf="parent"
app:layout_constraintTop_toBottomOf="@+id/tv_title"
app:layout_constraintVertical_bias="1.0" />
<TextView
android:id="@+id/tv_title"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="webview 学习实例"
android:textColor="#03A9F4"
android:textSize="25sp"
app:layout_constraintEnd_toEndOf="parent"
app:layout_constraintStart_toStartOf="parent"
app:layout_constraintTop_toTopOf="parent" />
</androidx.constraintlayout.widget.ConstraintLayout>
视图文件中用webview组件来展示网页
.java文件
public class WebView_learning extends AppCompatActivity {
private WebView webView;
private TextView textView;
private long exitTime = 0;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_web_view_learning);
textView = findViewById(R.id.tv_title);
webView = findViewById(R.id.webview);
webView.setWebChromeClient(new WebChromeClient(){
//在此处设置获取到的网站title
@Override
public void onReceivedTitle(WebView view, String title) {
super.onReceivedTitle(view, title);
textView.setText(title);
}
});
webView.setWebChromeClient(new WebChromeClient(){
//设置在webview点击新的网页但是仅仅在当前页面展示,不跳转到新的浏览器中去
public boolean shouldOverrideUrlLoading(WebView view, String url) {
view.loadUrl(url);
return true;
}
});
WebSettings settings = webView.getSettings();
settings.setUseWideViewPort(true);
settings.setLoadWithOverviewMode(true); //设置自适应屏幕
settings.setBuiltInZoomControls(true);
settings.setDisplayZoomControls(true);
settings.setSupportZoom(true); //设置支持缩放
settings.setJavaScriptEnabled(true);
webView.loadUrl("https://developer.android.google.cn/");
}
/*
我们需要重写回退按钮的时间,当用户点击回退按钮
1.webview.canGoBack()来判断网页是否可以后退,可以则goback()
2.如果不可以连续点击两次来退出APP,否则弹出弹窗
*/
public void onBackPressed(){
if (webView.canGoBack()){
webView.goBack();
}else {
if ((System.currentTimeMillis() - exitTime) > 2000){
Toast.makeText(getApplicationContext(),"再按一次退出",Toast.LENGTH_LONG).show();
exitTime = System.currentTimeMillis();
}else {
super.onBackPressed();
}
}
}
}
通过调用接口来实现APP中对网页的调用