温馨提示×

android toast的用法有哪些

小亿
108
2023-08-15 11:50:38
栏目: 编程语言

Android中Toast的用法有以下几种:

1.显示短时间的提示信息:使用Toast.makeText(context, text, Toast.LENGTH_SHORT).show();方法来显示一个短时间的提示信息。

示例代码:

Toast.makeText(getApplicationContext(), "短时间提示信息", Toast.LENGTH_SHORT).show();

2.显示长时间的提示信息:使用Toast.makeText(context, text, Toast.LENGTH_LONG).show();方法来显示一个长时间的提示信息。

示例代码:

Toast.makeText(getApplicationContext(), "长时间提示信息", Toast.LENGTH_LONG).show();

3.自定义显示位置的提示信息:使用setGravity()方法来设置Toast的显示位置。

示例代码:

Toast toast = Toast.makeText(getApplicationContext(), "自定义位置提示信息", Toast.LENGTH_SHORT);
toast.setGravity(Gravity.TOP|Gravity.LEFT, 0, 0); // 设置Toast在屏幕顶部左侧显示
toast.show();

4.自定义布局的提示信息:通过自定义布局文件来显示Toast的内容。

示例代码:

LayoutInflater inflater = getLayoutInflater();
View layout = inflater.inflate(R.layout.custom_toast_layout, findViewById(R.id.custom_toast_container));
TextView text = layout.findViewById(R.id.text);
text.setText("自定义布局提示信息");
Toast toast = new Toast(getApplicationContext());
toast.setGravity(Gravity.CENTER, 0, 0);
toast.setDuration(Toast.LENGTH_SHORT);
toast.setView(layout);
toast.show();

以上是几种常见的Toast用法,可以根据自己的需求选择合适的方式来显示提示信息。

0