Toast的其他用法(带图片的toast)

来源:互联网 发布:apache 微服务 框架 编辑:程序博客网 时间:2024/05/29 17:08

做安卓开发也很长时间了,但是对于toast的使用还是只是停留在Toast.maketext()的阶段;所以抽出半天时间看了几篇文章,自己写了个简单的demo,练习一下toast的其他用法!

1,带图片的toast;

这里写图片描述

Toast toast = Toast.makeText(getApplicationContext(), "带图片显示", Toast.LENGTH_LONG);//实例化toast对象LinearLayout toast_layout = (LinearLayout) toast.getView();ImageView imageView = new ImageView(getApplicationContext());imageView.setBackgroundResource(R.drawable.run);AnimationDrawable background = (AnimationDrawable) imageView.getBackground();background.start();toast_layout.addView(imageView, 0);toast.show();

主要步骤是:
1.实例化对象
2.获取Toast对象的布局,(之所以强转成linearLayout是因为源码中,toast默认布局就是一个线性布局)
3.创建imageview对象,并对其进行设置
4.将imageview添加到toast的布局中
5.将新的toast布局show出来

2,改变显示位置的toast;

这里写图片描述

Toast toast = Toast.makeText(getApplicationContext(), "改变位置", Toast.LENGTH_LONG);toast.setGravity(Gravity.CENTER, -100, 0);toast.show();

这里主要就是一个方法setGravity;
第一个参数是设置对应的gravity,第二个参数是水平方向的偏移量,第三个参数是竖直方向偏移量

3,完全自定义布局的toast

这里写图片描述

toast = new Toast(getApplicationContext());RelativeLayout inflate = (RelativeLayout) View.inflate(getApplicationContext(), R.layout.toast, null);toast.setView(inflate);toast.show();

如果简单的线性布局不能满足你的项目需求时,这时候就需要自定义Toast的布局了!然后通过setview的方法把新布局设置给toast就可以了.

另外,toast也可以手动取消的!只需要调用toast.cancle();方法就可以了!
源码点击下载

0 0
原创粉丝点击