Computer >> Hướng Dẫn Máy Tính >  >> Lập Trình >> Android

Cách bật nút Back (quay lại) cho WebView Android

Giới thiệu

Hướng dẫn này trình bày cách xử lý nút Back vật lý/hệ thống để điều hướng lùi trong lịch sử WebView thay vì thoát ứng dụng ngay lập tức.

Các bước thực hiện

Bước 1: Tạo dự án mới

Tạo dự án Android Studio: File → New Project.

Bước 2: Layout activity_main.xml

<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="https://schemas.android.com/apk/res/android"
    xmlns:app="https://schemas.android.com/apk/res-auto"
    xmlns:tools="https://schemas.android.com/tools"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    android:orientation="vertical"
    tools:context=".MainActivity">

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

</LinearLayout>

Bước 3: MainActivity.java

package com.example.myapplication;

import android.os.Build;
import android.os.Bundle;
import androidx.appcompat.app.AppCompatActivity;
import android.webkit.WebChromeClient;
import android.webkit.WebSettings;
import android.webkit.WebView;
import android.webkit.WebViewClient;
import android.app.ProgressDialog;

public class MainActivity extends AppCompatActivity {

    WebView webView;

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

        final ProgressDialog progressDialog = new ProgressDialog(this);
        progressDialog.setMessage("Đang tải dữ liệu...");
        progressDialog.setCancelable(false);

        webView = findViewById(R.id.web_view);
        webView.setVerticalScrollBarEnabled(true);
        webView.requestFocus();
        
        WebSettings webSettings = webView.getSettings();
        webSettings.setDefaultTextEncodingName("utf-8");
        webSettings.setJavaScriptEnabled(true);
        
        webView.loadUrl("https://touch.facebook.com/");

        webView.setWebViewClient(new WebViewClient() {
            @Override
            public boolean shouldOverrideUrlLoading(WebView view, String url) {
                view.loadUrl(url);
                return true;
            }
        });

        webView.setWebChromeClient(new WebChromeClient() {
            @Override
            public void onProgressChanged(WebView view, int newProgress) {
                if (newProgress < 100) {
                    progressDialog.show();
                }
                if (newProgress == 100) {
                    progressDialog.dismiss();
                }
            }
        });
    }

    // XỬ LÝ NÚT BACK
    @Override
    public void onBackPressed() {
        if (webView != null && webView.canGoBack()) {
            webView.goBack(); // Quay lại trang trước trong lịch sử WebView
        } else {
            super.onBackPressed(); // Thoát ứng dụng nếu không còn lịch sử
        }
    }
}

Bước 4: AndroidManifest.xml

<?xml version="1.0" encoding="utf-8"?>
<manifest xmlns:android="https://schemas.android.com/apk/res/android"
    package="com.example.myapplication">

    <uses-permission android:name="android.permission.INTERNET"/>

    <application
        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>
                

Giải thích cơ chế

  • webView.canGoBack(): Kiểm tra xem có trang trước trong lịch sử không.
  • webView.goBack(): Điều hướng về trang trước.
  • super.onBackPressed(): Gọi hành vi mặc định (thoát Activity/ứng dụng).

Mở rộng: Xử lý nút Forward

// Thêm menu hoặc button để đi tới trang sau
public boolean onOptionsItemSelected(MenuItem item) {
    if (item.getItemId() == R.id.action_forward && webView.canGoForward()) {
        webView.goForward();
        return true;
    }
    return super.onOptionsItemSelected(item);
}

Lưu ý quan trọng

  • Luôn kiểm tra webView != null trước khi gọi phương thức.
  • Xử lý này cải thiện trải nghiệm người dùng đáng kể cho ứng dụng WebView-based.
  • Có thể kết hợp với onKeyDown(KeyEvent.KEYCODE_BACK, event) cho các phiên bản Android cũ.