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

Tùy chỉnh Toast message trong Android

Toast mặc định của Android khá đơn giản: text nhỏ, nền đen bán trong, vị trí cố định dưới cùng. Custom Toast cho phép thiết kế giao diện tùy ý: hình ảnh, màu sắc, layout phức tạp, vị trí tùy chỉnh.

Các bước tạo Custom Toast

Bước 1: Tạo project mới

Bước 2: Layout activity_main.xml - Nút bấm

<?xml version="1.0" encoding="utf-8"?>
<androidx.constraintlayout.widget.ConstraintLayout
    xmlns:android="https://schemas.android.com/apk/res/android"
    android:layout_width="match_parent"
    android:layout_height="match_parent">

    <Button
        android:id="@+id/btnShowToast"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:text="Hiển thị Custom Toast"
        app:layout_constraintBottom_toBottomOf="parent"
        app:layout_constraintLeft_toLeftOf="parent"
        app:layout_constraintRight_toRightOf="parent"
        app:layout_constraintTop_toTopOf="parent" />
</androidx.constraintlayout.widget.ConstraintLayout>

Bước 3: Layout custom_toast.xml - Giao diện tùy chỉnh

<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="https://schemas.android.com/apk/res/android"
    android:id="@+id/custom_toast_container"
    android:layout_width="wrap_content"
    android:layout_height="wrap_content"
    android:background="@drawable/toast_background"
    android:orientation="horizontal"
    android:padding="12dp"
    android:gravity="center">

    <ImageView
        android:id="@+id/toastIcon"
        android:layout_width="40dp"
        android:layout_height="40dp"
        android:src="@drawable/ic_check_circle"
        android:contentDescription="Icon" />

    <TextView
        android:id="@+id/toastText"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:layout_marginStart="12dp"
        android:text="Thành công!"
        android:textColor="#FFFFFF"
        android:textSize="16sp"
        android:textStyle="bold" />
</LinearLayout>

Bước 4: Drawable toast_background.xml (res/drawable/)

<?xml version="1.0" encoding="utf-8"?>
<shape xmlns:android="https://schemas.android.com/apk/res/android"
    android:shape="rectangle">
    <corners android:radius="12dp" />
    <gradient
        android:angle="45"
        android:startColor="#4CAF50"
        android:endColor="#2E7D32"
        android:type="linear" />
    <padding
        android:left="16dp"
        android:top="12dp"
        android:right="16dp"
        android:bottom="12dp" />
    <stroke
        android:width="1dp"
        android:color="#1B5E20" />
</shape>

Bước 5: MainActivity.java - Hiển thị Custom Toast

import android.os.Bundle;
import android.view.Gravity;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.Button;
import android.widget.TextView;
import android.widget.Toast;
import androidx.appcompat.app.AppCompatActivity;

public class MainActivity extends AppCompatActivity {
    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);

        Button btnShowToast = findViewById(R.id.btnShowToast);
        btnShowToast.setOnClickListener(v -> showCustomToast("Đã lưu thành công!", R.drawable.ic_check_circle));
    }

    private void showCustomToast(String message, int iconResId) {
        // Inflate custom layout
        LayoutInflater inflater = getLayoutInflater();
        View layout = inflater.inflate(R.layout.custom_toast, 
            (ViewGroup) findViewById(R.id.custom_toast_container));

        // Cập nhật nội dung
        TextView textView = layout.findViewById(R.id.toastText);
        textView.setText(message);
        
        // Có thể đổi icon theo loại thông báo
        // ImageView iconView = layout.findViewById(R.id.toastIcon);
        // iconView.setImageResource(iconResId);

        // Tạo và cấu hình Toast
        Toast toast = new Toast(getApplicationContext());
        toast.setDuration(Toast.LENGTH_LONG);
        toast.setGravity(Gravity.BOTTOM | Gravity.CENTER_HORIZONTAL, 0, 100); // Vị trí tùy chỉnh
        toast.setView(layout);
        toast.show();
    }
}

Các loại Custom Toast thường dùng

1. Toast thành công (Success)

Màu xanh lá, icon check circle

2. Toast lỗi (Error)

// toast_error_background.xml
<shape xmlns:android="https://schemas.android.com/apk/res/android">
    <solid android:color="#F44336" />
    <corners android:radius="12dp" />
</shape>

// Sử dụng icon: ic_error, ic_warning

3. Toast cảnh báo (Warning)

// Màu cam/vàng
// Icon: ic_warning_amber

4. Toast thông tin (Info)

// Màu xanh dương
// Icon: ic_info

Helper class tái sử dụng

public class CustomToast {
    public static void showSuccess(Context context, String message) {
        show(context, message, R.drawable.ic_check_circle, R.drawable.toast_bg_success);
    }
    
    public static void showError(Context context, String message) {
        show(context, message, R.drawable.ic_error, R.drawable.toast_bg_error);
    }
    
    public static void showWarning(Context context, String message) {
        show(context, message, R.drawable.ic_warning, R.drawable.toast_bg_warning);
    }
    
    public static void showInfo(Context context, String message) {
        show(context, message, R.drawable.ic_info, R.drawable.toast_bg_info);
    }
    
    private static void show(Context context, String message, int iconRes, int bgRes) {
        LayoutInflater inflater = LayoutInflater.from(context);
        View layout = inflater.inflate(R.layout.custom_toast, null);
        
        TextView tv = layout.findViewById(R.id.toastText);
        tv.setText(message);
        layout.setBackgroundResource(bgRes);
        // layout.findViewById(R.id.toastIcon).setBackgroundResource(iconRes);
        
        Toast toast = new Toast(context);
        toast.setDuration(Toast.LENGTH_SHORT);
        toast.setGravity(Gravity.BOTTOM | Gravity.CENTER_HORIZONTAL, 0, 100);
        toast.setView(layout);
        toast.show();
    }
}

// Sử dụng: CustomToast.showSuccess(this, "Đăng nhập thành công!");

Chạy ứng dụng

Nhấn nút "Hiển thị Custom Toast" → Toast tùy chỉnh xuất hiện ở dưới cùng, giữa màn hình, với background gradient xanh, text trắng, icon check.

Lưu ý

  • Toast.LENGTH_SHORT (~2s) hoặc LENGTH_LONG (~3.5s)
  • setGravity() cho phép đặt vị trí chính xác (xOffset, yOffset)
  • Custom Toast vẫn tuân thủ quy tắc: không chặn tương tác, tự động biến mất
  • Android 11+ hạn chế custom toast từ background - chỉ dùng trong Activity/Foreground service
  • Cân nhắc dùng Snackbar cho action quan trọng (có nút bấm)