Toast toast = Toast.makeText(getApplicationContext(), "Hello World!", Toast.LENGTH_SHORT); toast.show(); // Cancel the toast message after a delay of 1000 milliseconds (1 second) new Handler().postDelayed(new Runnable() { @Override public void run() { toast.cancel(); } }, 1000);
// Declare a class-level Toast variable private Toast toast; // Method to show a Toast message private void showToast(String message) { // Cancel any currently showing toasts if (toast != null) { toast.cancel(); } // Create and show the new Toast message toast = Toast.makeText(getApplicationContext(), message, Toast.LENGTH_SHORT); toast.show(); }This code declares a class-level Toast variable and a method to show Toast messages. The method cancels any currently showing toasts before creating and showing the new Toast message. This prevents multiple Toast messages from being displayed on top of each other. The package library for the android.widget Toast class is android.widget.