Toasts in Android are used to display brief, auto-dismissing pop-up messages to the user. They’re a great way to provide feedback without interrupting the user’s flow. In this blog, we’ll learn how to use Toasts in an Android app using Java.
Getting Started
First, you need to have Android Studio installed on your computer. If you haven’t installed it yet, you can download it from the official Android Developer website.
Creating a Toast
Creating a Toast in Android is quite simple. Here’s how you can do it:
Toast.makeText(getApplicationContext(), "This is a Toast message", Toast.LENGTH_SHORT).show();
In the above code, getApplicationContext()
is the context, "This is a Toast message"
is the message that you want to show, and Toast.LENGTH_SHORT
is the duration for which the toast should be shown. The show()
method is used to display the toast.
Customizing a Toast
You can also customize a Toast by setting a custom view to it. Here’s how you can do it:
Toast toast = new Toast(getApplicationContext());
LayoutInflater inflater = getLayoutInflater();
View view = inflater.inflate(R.layout.toast_layout, (ViewGroup) findViewById(R.id.toast_root));
toast.setView(view);
toast.setDuration(Toast.LENGTH_LONG);
toast.show();
In the above code, we first create a new Toast. Then we get the LayoutInflater
and use it to inflate our custom layout toast_layout
. We then set this view to our toast, set the duration, and show the toast.