您的位置:首页 > 移动开发 > Android开发

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

2016-04-14 16:42 357 查看
做安卓开发也很长时间了,但是对于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();方法就可以了!

源码点击下载
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签:  android toast