一、基本用法
//参数一:上下文
//参数二:Toast要显示的内容
//参数三:Toast显示的时间
Toast.makeText(MainActivity.this,"Toast",Toast.LENGTH_SHORT).show();
二、带图片的Toast
Toast toast = Toast.makeText(MainActivity.this, "Toast", Toast.LENGTH_SHORT);
//通过toast创建LinearLayout容器
LinearLayout layout = (LinearLayout) toast.getView();
//创建图片
ImageView iv = new ImageView(MainActivity.this);
iv.setImageResource(R.mipmap.ic_launcher);
//添加图片到Toast布局
layout.addView(iv);
toast.show();
三、使用自定义布局显示Toast
LayoutInflater inflater = getLayoutInflater();
View view1 = inflater.inflate(R.layout.layout_toast, null);
Toast toast = new Toast(MainActivity.this);
toast.setView(view1);
toast.setDuration(Toast.LENGTH_SHORT);
toast.show();
四、防止重复点击弹出多次
1,首先将Toast封装成一个公共方法,判断当Toast为空时新建Toast对象,当Toast不为空时,设置Toast的内容。
封装成方法:
public class Utils {
private static Toast toast;
public static void showToast(Context context, String content) {
if (toast == null) {
toast = Toast.makeText(context, content, Toast.LENGTH_SHORT);
} else {
toast.setText(content);
}
toast.show();
}
}
调用:
Utils.showToast(this, "点击了按钮");