To show a toast message in an Android app, you can use the Toast
class provided by the Android framework. A toast is a small pop-up message that appears on the screen for a short period of time and disappears automatically.
To show a toast message, you can use the following code:
Toast.makeText(getApplicationContext(), "This is a toast message", Toast.LENGTH_SHORT).show();
The makeText()
method takes three arguments:
Context
object, which is used to access the app's resources and perform operations that need a context. You can use getApplicationContext()
to get the current application context.CharSequence
object representing the message to be displayed in the toast.int
value representing the duration of the toast. The possible values are Toast.LENGTH_SHORT
(for a short duration) and Toast.LENGTH_LONG
(for a longer duration).The show()
method is then called to display the toast on the screen.
You can also customize the appearance of the toast by setting its gravity and offset, or by creating a custom layout for the toast.
Here is an example of a custom toast layout:
LayoutInflater inflater = getLayoutInflater(); View layout = inflater.inflate(R.layout.custom_toast, (ViewGroup) findViewById(R.id.custom_toast_container)); TextView text = layout.findViewById(R.id.text); text.setText("This is a custom toast message"); Toast toast = new Toast(getApplicationContext()); toast.setGravity(Gravity.CENTER_VERTICAL, 0, 0); toast.setDuration(Toast.LENGTH_LONG); toast.setView(layout); toast.show();
In this example, a layout XML file called custom_toast.xml
is used to define the appearance of the toast. The layout file should contain a root element with an ID of custom_toast_container
, which will be inflated and set as the view for the toast.