Android学习笔记之Toast

使用统一标准化的Toast

Toast.makeText(Context context, CharSequence text, int duration).show();
/*
android.widget.Toast

context: this & MainActivity & getApplicationContext()
text: 想要输出的通知文本
duration: LENGTH_LONG & LENGTH_SHORT
*/

android. widget. Toast类的show()方法可以显示这个通知。

可以对这条通知显示的位置进行自定义。

Toast toast = Toast.makeText(getApplicationContext(), "Hi", Toast.LENGTH_SHORT);
toast.setGravity(Gravity.BOTTOM | Gravity.LEFT, 0, 0);
toast.show();

在这里插入图片描述

创建自定义Toast

如果仅仅是只有统一样式的Toast是不是觉得太单调了呀?
通过特殊的部件或布局显示Toast消息。这样可以自定义Toast,制作不同样式的Toast。

首先,为这个Toast创建样式,方法与普通UI相同。
其次,创建一个View,把Toast的样式置入。

View ToastView = getCustomToastView(R.drawable.ic_launcher, "Test Application", "Hello");
Toast toast = new Toast(getApplicationContext());
toast.setView(ToastView);
toast.show();

cToast.xml是定义Toast样式的文件。

public View getCustomToastView(int imageResourceID, String ToastTitle, String Message){
	LayoutInflater inflater = getLayoutInflater();
	View ToastView = inflater.inflate(R.layout.cToast, (ViewGroup)findViewById(R.id.cToast));
	ImageView image = (ImageView)ToastView.findViewById(R.id.ivToastImage);
	image.setImageResource(R.drawable.ic_launcher);
	TextView title = (TextView)ToastView.findViewById(R.id.tvToastTitle);
	title.setText(ToastTitle);
	TextView text = (TextView)ToastView.findViewById(R.id.tvToastText);
	text.setText(Message);
	return ToaseView;
}

这就是最终我们做出来的自定义Toast的样式啦。(虽然有点丑)
在这里插入图片描述

发布了1 篇原创文章 · 获赞 2 · 访问量 12

猜你喜欢

转载自blog.csdn.net/weixin_44043504/article/details/105440807