Android toast用法
时间: 2023-11-03 16:03:13 浏览: 45
Android toast是一种短暂地在屏幕上显示信息的方式。它通常用于向用户提供简短的提示或指导。下面是一些常用的Android toast用法:
1. 显示简单的文本提示
Toast.makeText(context, "Hello World!", Toast.LENGTH_SHORT).show();
2. 显示长文本提示(使用LENGTH_LONG)
String longText = "This is a long text message that will be displayed in a toast.";
Toast.makeText(context, longText, Toast.LENGTH_LONG).show();
3. 显示带图标的文本提示(使用setCompoundDrawables())
Toast toast = Toast.makeText(context, "Hello World!", Toast.LENGTH_SHORT);
TextView toastTextView = toast.getView().findViewById(android.R.id.message);
Drawable icon = context.getResources().getDrawable(R.drawable.ic_launcher);
toastTextView.setCompoundDrawablesWithIntrinsicBounds(icon, null, null, null);
toast.show();
4. 定制toast的显示位置(使用setGravity())
Toast toast = Toast.makeText(context, "Hello World!", Toast.LENGTH_SHORT);
toast.setGravity(Gravity.CENTER, 0, 0);
toast.show();
希望能解决您的问题!