自定义重写Toast

来源:互联网 发布:android 查看端口号 编辑:程序博客网 时间:2024/05/01 16:08
使用方法以及说明写在代码中的注释中
/** *  * @author liu *本类调用方法new MyToast(context, "送积分:", "200", 20).showLonger(); */public class MyToast extends Toast {    public MyToast(Context context, String message,String creit, int textsize) {            super(context);        if (context == null) {            return;        }        //设置外层容器        RelativeLayout mainLayout = new RelativeLayout(context);        ViewGroup.LayoutParams mainP = new ViewGroup.LayoutParams (ViewGroup.LayoutParams.FILL_PARENT, ViewGroup.LayoutParams.WRAP_CONTENT);        mainLayout.setLayoutParams(mainP);        try {        //从assets文件夹中进行图片加载InputStream open = context.getResources().getAssets().open("toast.png");Drawable background=Drawable.createFromStream(open, "toast.png");mainLayout.setBackground(background);} catch (IOException e) {//找不到图片或者加载异常时设置背景色为黑色mainLayout.setBackgroundColor(Color.BLACK);}                TextView content = new TextView(context);        //PhoneUtil.getResolution(context)为获取屏幕分辨率的方法,根据屏幕的宽度计算toast显示的宽度        int width=PhoneUtil.getResolution(context)[0]/2;        int height=(width*2)/5;        //设置宽和高        RelativeLayout.LayoutParams contentP = new RelativeLayout.LayoutParams(width,height);        content.setLayoutParams(contentP);        //toast中显示的内容        String str=message+creit;        SpannableStringBuilder style=new SpannableStringBuilder(str);         //对于toast中的文字设置不同的颜色,message设置为白色,creit设置为红色        style.setSpan(new ForegroundColorSpan(Color.WHITE),0,message.length()-1,Spannable.SPAN_EXCLUSIVE_EXCLUSIVE);  //设置字体大小        style.setSpan(new AbsoluteSizeSpan(60), message.length(), str.length(),Spannable.SPAN_EXCLUSIVE_EXCLUSIVE);                style.setSpan(new ForegroundColorSpan(Color.RED),message.length(),str.length(),Spannable.SPAN_EXCLUSIVE_EXCLUSIVE);                  content.setText(style);        content.setTextSize(textsize);        //设置字体居中        content.setGravity(Gravity.CENTER);        mainLayout.addView(content);        //给字体设置动画效果        TranslateAnimation alphaAnimation2 = new TranslateAnimation(-20f, 0, 0, 0);        alphaAnimation2.setDuration(90);        alphaAnimation2.setRepeatCount(9);        alphaAnimation2.setRepeatMode(Animation.REVERSE);        content.setAnimation(alphaAnimation2);        alphaAnimation2.start();        //Utils.convertToScreenPixels为根据分辨率及显示密度计算显示数值的方法        setGravity(Gravity.BOTTOM, 0, Utils.convertToScreenPixels(70, 1));        setDuration(Toast.LENGTH_LONG);//设置长显示        setView(mainLayout);    }        public void showLonger() {    //把Toast.show添加到消息队列中并显示        new Handler().postDelayed(new Runnable() {            @Override            public void run() {                show();            }        //显示延迟时间        }, 1000);            }}


原创粉丝点击