Toast是一种提供给用户简洁信息的视图。Toast类帮助你创建和显示该信息。
该视图已浮于应用程序之上的形式呈现给用户。因为它并不获得焦点,即使用户正在输入什么也不会受到影响。它的目标是尽可能已不显眼的方式,使用户看到你提供的信息。有两个例子就是音量控制和设置信息保存成功。
默认的样式:
case R.id.
btn_default:
Toast. makeText(getApplicationContext(), "这是默认样式Toast",Toast. LENGTH_SHORT).show();
Toast. makeText(getApplicationContext(), "这是默认样式Toast",Toast. LENGTH_SHORT).show();
break;
自定义位置:
case R.id.
btn_define:
toast = Toast. makeText(getApplicationContext(), "这是自定义位置",Toast. LENGTH_LONG);
toast.setGravity(Gravity. CENTER, 0, 0);
toast.show();
toast = Toast. makeText(getApplicationContext(), "这是自定义位置",Toast. LENGTH_LONG);
toast.setGravity(Gravity. CENTER, 0, 0);
toast.show();
break;
带图片的Toast:
case R.id.
btn_image_define:
toast = Toast. makeText(getApplicationContext(), "这是带图片的Toast",Toast. LENGTH_LONG);
LinearLayout toastView = (LinearLayout) toast.getView();
ImageView image = new ImageView(getApplicationContext());
image.setImageResource(R.mipmap. ic_launcher);
toastView.addView(image, 0);
toast.show();
toast = Toast. makeText(getApplicationContext(), "这是带图片的Toast",Toast. LENGTH_LONG);
LinearLayout toastView = (LinearLayout) toast.getView();
ImageView image = new ImageView(getApplicationContext());
image.setImageResource(R.mipmap. ic_launcher);
toastView.addView(image, 0);
toast.show();
break;
完全自定义的:
case R.id.
btn_all_define:
LayoutInflater inflater = getLayoutInflater();
View view = inflater.inflate(R.layout.custom, null);//这里要注意的一点,在获取到自己写好的布局是,在以下的引用中记得要在该布局下寻找
ImageView iv = (ImageView)view.findViewById(R.id.
ivToast);//在view布局中找到ImageView
iv.setImageResource(R.mipmap.ic_launcher);
TextView title = (TextView) view.findViewById(R.id.tcTitleToast);//在view布局中找到TextView
title.setText(
"完全自定义Toast标题");
TextView text = (TextView) view.findViewById(R.id.tvToast);//在view布局中找到TextView
text.setText(
"完全自定义Toast");
toast = new Toast(getApplicationContext());
toast.setGravity(Gravity.RIGHT | Gravity.TOP, 11, 40);//设置显示的位置
toast.setDuration(Toast.LENGTH_LONG);//设置显示的时长,也可以是1000(毫秒)
toast.setView(view);//最后再设置以下View
toast.show();
break;
其他线程显示:
case R.id.
btn_other_thread:
new Thread( new Runnable() {
@Override
public void run() {
showToast();
}
}).start();
new Thread( new Runnable() {
@Override
public void run() {
showToast();
}
}).start();
break;
public void showToast(){
handler.post( new Runnable() {
@Override
public void run() {
Toast. makeText(getApplicationContext(), "我来自其他线程",Toast. LENGTH_SHORT).show();
}
});
}
handler.post( new Runnable() {
@Override
public void run() {
Toast. makeText(getApplicationContext(), "我来自其他线程",Toast. LENGTH_SHORT).show();
}
});
}