安卓自定义Toast:
1.自定义一个类:CustomToast 继承自:Toast
2.在CustomToast类中 添加一个静态 mCustomToast 对象
private static CustomToast mCustomToast;
3.在CustomToast类中 添加一个静态方法;
public static void show(Context context, String text) {
if (TextUtils.isEmpty(text)) { return; }
try {
cancelToast();
mCustomToast = new CustomToast(context);
View layout = View.inflate(context, R.layout.toast_layout, null);
RelativeLayout toastLayout = layout.findViewById(R.id.toast_layout);
TextView toastText = layout.findViewById(R.id.toast_text);
toastText.setText(text);
mCustomToast.setView(layout);
mCustomToast.setGravity(Gravity.FILL_HORIZONTAL, 0, 1);
mCustomToast.setDuration(Toast.LENGTH_SHORT);
ObjectAnimator animator = ObjectAnimator.ofFloat(toastLayout, "translationY", 200, 0);
animator.setDuration(200);
animator.start();
mCustomToast.show();
} catch (Exception e) {
e.printStackTrace();
}
}
4.外部调用:
CustomToast.show(this, "I am custom toast");
这样任何样式的Toast都可以自定义了
Demo地址:https://github.com/HuaDanJson/CustomToast
本文详细介绍了如何在安卓应用中自定义Toast样式,通过创建CustomToast类并继承Toast,实现可自定义显示位置、动画效果及持续时间的Toast。外部调用简单,只需一行代码即可展示自定义Toast。

1万+

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



