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

Cách đặt thời gian Toast dài hơn Toast.LENGTH_LONG trong Android

Giới thiệu

Android chỉ cung cấp hai độ dài Toast cố định: LENGTH_SHORT (~2 giây) và LENGTH_LONG (~3.5 giây). Ví dụ này minh họa cách hiển thị Toast lâu hơn (10 giây) bằng cách lặp lại hiển thị với CountDownTimer.

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

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

Mở Android Studio, chọn File → New Project.

Bước 2: Thiết kế giao diện (res/layout/activity_main.xml)

<?xml version="1.0" encoding="utf-8"?>
<androidx.constraintlayout.widget.ConstraintLayout
    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"
    tools:context=".MainActivity">

    <TextView
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:text="Hello World!"
        app:layout_constraintBottom_toBottomOf="parent"
        app:layout_constraintLeft_toLeftOf="parent"
        app:layout_constraintRight_toRightOf="parent"
        app:layout_constraintTop_toTopOf="parent" />

    <androidx.appcompat.widget.AppCompatButton
        android:layout_width="match_parent"
        android:layout_height="match_parent"
        android:onClick="showToast" />

</androidx.constraintlayout.widget.ConstraintLayout>

Bước 3: Viết code logic (src/MainActivity.java)

package com.app.sample;

import androidx.appcompat.app.AppCompatActivity;
import android.os.Bundle;
import android.os.CountDownTimer;
import android.view.View;
import android.widget.Toast;

public class MainActivity extends AppCompatActivity {
    private Toast mToastToShow;

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

    public void showToast(View view) {
        int toastDurationInMilliSeconds = 10000; // 10 giây
        mToastToShow = Toast.makeText(this, "Hello world, I am a long toast.", Toast.LENGTH_LONG);

        CountDownTimer toastCountDown = new CountDownTimer(toastDurationInMilliSeconds, 1000) {
            @Override
            public void onTick(long millisUntilFinished) {
                mToastToShow.show(); // Hiển thị lại mỗi giây
            }

            @Override
            public void onFinish() {
                mToastToShow.cancel(); // Hủy khi hết thời gian
            }
        };

        mToastToShow.show();
        toastCountDown.start();
    }
}

Bước 4: Cấu hình Manifest (Manifests/AndroidManifest.xml)

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

    <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>
                <action android:name="android.intent.action.MAIN" />
                <category android:name="android.intent.category.LAUNCHER" />
            </intent-filter>
        </activity>

    </application>
</manifest>

Chạy ứng dụng

Kết nối thiết bị, nhấn Run. Nhấn vào màn hình (button ẩn) để hiển thị Toast 10 giây.

Cách đặt thời gian Toast dài hơn Toast.LENGTH_LONG trong Android

Các giải pháp thay thế tốt hơn

1. Snackbar (Material Design - khuyến nghị)

Snackbar.make(view, "Thông báo dài", Snackbar.LENGTH_INDEFINITE)
        .setAction("Đóng", v -> {})
        .show();

Snackbar hỗ trợ LENGTH_INDEFINITE (hiện đến khi người dùng tác động) và tuân thủ Material Design.

2. Custom Dialog / BottomSheetDialogFragment

Tạo Dialog tùy chỉnh với layout riêng, có nút đóng, không bị giới hạn thời gian.

3. Thư viện Toasty / SuperToasts

Các thư viện open-source cho phép tùy chỉnh duration, icon, màu sắc, vị trí.

Lưu ý

Cách dùng CountDownTimer lặp show() có nhược điểm: Toast có thể nhấp nháy, không mượt mà trên một số thiết bị. Ưu tiên Snackbar hoặc Custom View cho UX tốt hơn.