Android Toast(五种)
1. 默认效果
代码:
Toast.makeText(getApplicationContext(), "默认Toast样式",
Toast.LENGTH_SHORT).show();
2.自定义显示位置效果
代码:
toast = Toast.makeText(getApplicationContext(),
"自定义位置Toast", Toast.LENGTH_LONG);
//设置Toast位置
toast.setGravity(Gravity.CENTER, 0, 0);
toast.show();
3. 带图片效果:
代码
toast = Toast.makeText(getApplicationContext(),
"带图片的Toast", Toast.LENGTH_LONG);
//设置Toast位置
toast.setGravity(Gravity.CENTER, 0, 0);
LinearLayout toastView = (LinearLayout) toast.getView();
ImageView imageCodeProject = new ImageView(getApplicationContext());
imageCodeProject.setImageResource(R.drawable.icon);
//添加图片
toastView.addView(imageCodeProject, 0);
toast.show();
4.完全自定义效果:
代码
//将布局XML文件转换为View
LayoutInflater inflater = getLayoutInflater();
View layout = inflater.inflate(R.layout.custom,
(ViewGroup) findViewById(R.id.llToast));
//编辑布局样式
ImageView image = (ImageView) layout
.findViewById(R.id.tvImageToast);
image.setImageResource(R.mipmap.ic_launcher);
TextView title = (TextView) layout.findViewById(R.id.tvTitleToast);
title.setText("Attention");
TextView text = (TextView) layout.findViewById(R.id.tvTextToast);
text.setText("完全自定义Toast");
toast = new Toast(getApplicationContext());
//设置Toast位置
toast.setGravity(Gravity.RIGHT | Gravity.TOP, 12, 40);
//设置持续时间
toast.setDuration(Toast.LENGTH_LONG);
//设置oast视图
toast.setView(layout);
toast.show();
5. 在其它线程中执行
new Thread(new Runnable() {
public void run() {
//执行此方法完成Toast打印(在Avtivity中写的)
showToast();
}
}).start();

本文详细介绍了五种实现 Android Toast 的方法,包括默认样式、自定义位置、带图片、完全自定义样式及在其他线程中执行的方法。通过具体代码示例展示了如何灵活使用 Toast 来增强应用用户体验。
1943

被折叠的 条评论
为什么被折叠?



