自定义Toast背景和内容

一、编写一个Toast工具类

public class ToastUtils {

        private static Toasttoast =null;

        public static boolean isShow =true;


        private static void showMessageTwo(Context context, CharSequence message, boolean showicon) {

                cancelCurrentToast();

                if(toast ==null){

                        toast = Toast.makeText(context, message, Toast.LENGTH_SHORT);//创建Toast对象 

                        LinearLayout toastView = (LinearLayout)LayoutInflater.from(context).inflate(R.layout.toast_view, null);//获取自定义布局

                        TextView tv = toastView.findViewById(R.id.tv_toast);

                        ImageView iv_toast =toastView.findViewById(R.id.iv_toast);

                        tv.setText(message);

                        iv_toast.setVisibility(mShowicon ? View.VISIBLE : View.GONE);//设置图标是否显示

                        toast.setGravity(Gravity.LEFT, 200, 200);//设置显示的位置

                        toast.setView(toastView);

                }else {

                        TextView tv =toast.getView().findViewById(R.id.tv_toast);

                        tv.setText(message);

                }

                toast.show();

        }


//在需要吐司的地方调此方法进行显示

        public static void showTwo(Context context,CharSequence message, boolean showicon) {

                if(isShow && context !=null){

                        showMessageTwo(context,message, showicon);

                   }

        }


//先关闭当前显示的Toast

        public static void cancelCurrentToast() {

                if (toast !=null) {

                        toast.cancel();

                        toast =null;

                   }

        }

}

二、自定义的布局,布局根据需要自己定义

最后编辑于
©著作权归作者所有,转载或内容合作请联系作者
平台声明:文章内容(如有图片或视频亦包括在内)由作者上传并发布,文章内容仅代表作者本人观点,简书系信息发布平台,仅提供信息存储服务。