How to use Toast.makeText()

The method Toast.makeText() is used in Android to display short messages.

  1. Instantiate a Toast object:
  2. Create a toast message with the specified context, text, and duration.
  3. Context is usually a reference to the current Activity.
  4. text: Message to be displayed.
  5. Duration: Indicates the length of time, which can be either Toast.LENGTH_SHORT (brief display) or Toast.LENGTH_LONG (extended display).
  6. Set the position of the Toast (optional):
  7. Set the gravity, x offset, and y offset of the toast.
  8. The position at which the Toast is displayed can be Gravity.TOP (at the top), Gravity.BOTTOM (at the bottom), Gravity.CENTER (in the center), and so on.
  9. xOffset: offset on the x-axis.
  10. yOffset: the offset on the y-axis.
  11. Display a Toast message:
  12. display the toast message.

The complete example code is as follows:

// 在Activity的某个方法中调用Toast.makeText()
Toast toast = Toast.makeText(MainActivity.this, "Hello World!", Toast.LENGTH_SHORT);

// 设置Toast的位置
toast.setGravity(Gravity.CENTER, 0, 0);

// 显示Toast消息
toast.show();

This will display a short-duration Toast message in the center position.

bannerAds