How to use Toast.makeText()
The method Toast.makeText() is used in Android to display short messages.
- Instantiate a Toast object:
- Create a toast message with the specified context, text, and duration.
- Context is usually a reference to the current Activity.
- text: Message to be displayed.
- Duration: Indicates the length of time, which can be either Toast.LENGTH_SHORT (brief display) or Toast.LENGTH_LONG (extended display).
- Set the position of the Toast (optional):
- Set the gravity, x offset, and y offset of the toast.
- 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.
- xOffset: offset on the x-axis.
- yOffset: the offset on the y-axis.
- Display a Toast message:
- 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.