安卓自定义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