Toast.makeText(Context context, CharSequence text, @Duration int duration)
context
:当前的上下文环境。可用getApplicationContext()或this
text
:要显示的字符串。
duration
:显示的时间长短。Toast.LENGTH_LONG 3.5秒和Toast.LENGTH_SHORT 2秒,也可以使用毫秒如2000ms。
最后后面别忘了加.show()
Toast常用的几种方式:
//默认
Toast.makeText(this, string, Toast.LENGTH_SHORT).show();
//自定义位置
toast = Toast.makeText(this, string, Toast.LENGTH_LONG);
toast.setGravity(Gravity.CENTER, 0, 0);// 居中显示
toast.show();
//自定义图片
toast = Toast.makeText(this, string, Toast.LENGTH_LONG);
toast.setGravity(Gravity.TOP, 0, 0);// 最上方显示
LinearLayout toastLayout = (LinearLayout) toast.getView();
imageView = new ImageView(this);
imageView.setImageResource(R.drawable.ic_launcher);//图片文职
toastLayout.addView(imageView, 0);// 0 图片在文字的上方 , 1 图片在文字的下方
toast.show();
//完全自定义,需要创建一个xml模板
LayoutInflater inflater = getLayoutInflater();// LayoutInflater对象
View layout = inflater.inflate(R.layout.custom_view, null);
imageView = (ImageView) layout.findViewById(R.id.imageView);
TextView text = (TextView) layout.findViewById(R.id.textView);
imageView.setImageResource(R.drawable.ic_launcher);
text.setText(message.obj.toString());
toast = new Toast(getApplicationContext());
// 底部 、水平居中,X偏移50 Y偏移50
toast.setGravity(Gravity.CENTER_HORIZONTAL | Gravity.BOTTOM, 50, 50);
toast.setDuration(Toast.LENGTH_SHORT);
toast.setView(layout);
toast.show();
break;
参考:https://www.jianshu.com/p/0054d2c54c7a