Toast详解

来源:互联网 发布:ubuntu win7引导修复 编辑:程序博客网 时间:2024/05/18 01:01

 Toast是Android中用来显示显示信息的一种机制,和Dialog不一样的是,Toast是没有焦点的,而且Toast显示的时间有限,过一定的时间就会自动消失。而且Toast主要用于向用户显示提示消息,接下来为大家总结了Android五种Toast特效详解,当然大家也可以根据自己的需求来自定义自己想要的效果。

一、默认效果

代码:
Toast.makeText(getApplicationContext(), "默认Toast样式",Toast.LENGTH_SHORT).show();


二、自定义显示位置效果
代码:
toast = Toast.makeText(getApplicationContext(), "自定义位置Toast", Toast.LENGTH_LONG);toast.setGravity(Gravity.CENTER, 0, 0);toast.show();

三、带图片效果
代码:
toast = Toast.makeText(getApplicationContext(), "带图片的Toast", Toast.LENGTH_LONG);toast.setGravity(Gravity.CENTER, 0, 0);LinearLayout toastView = (LinearLayout) toast.getView();ImageView imageCodeProject = new ImageView(getApplicationContext());imageCodeProject.setImageResource(R.mipmap.ic_launcher);toastView.addView(imageCodeProject, 0);toast.show();

四、完全自定义显示位置效果
代码:
LayoutInflater inflater = getLayoutInflater();View layout = inflater.inflate(R.layout.custom, (ViewGroup) findViewById(R.id.llToast));ImageView image = (ImageView) layout.findViewById(R.id.tvImageToast);image.setImageResource(R.mipmap.ic_launcher);TextView title = (TextView) layout.findViewById(R.id.tvTitleToast);title.setText("Attention");TextView text = (TextView) layout.findViewById(R.id.tvTextToast);text.setText("完全自定义Toast");toast = new Toast(getApplicationContext());toast.setGravity(Gravity.CENTER, 0, 0);toast.setDuration(Toast.LENGTH_LONG);toast.setView(layout);toast.show();
五、来自其他线程
代码: 
handler = new Handler();new Thread(new Runnable(){    public void run()    {        showToast();    }}).start();
private void showToast() {    handler.post(new Runnable()    {        @Override        public void run()        {            Toast.makeText(getApplicationContext(), "Hello,I come from other thread!", 5000).show();        }    });}


如何设置Toast显示的位置

方法一:

setGravity(int gravity, int xOffset, int yOffset) 三个参数分别表示(起点位置,水平向右位移,垂直向下位移)

方法二:

setMargin(float horizontalMargin, float verticalMargin)
以横向和纵向的百分比设置显示位置,参数均为float类型(水平位移正右负左,竖直位移正上负下)

注意事项:

Toast中有一个public方法setText(),可以给toast设置resid或者string,该方式尽可以在我们的第一种方法中使用,第二种自定义toast的方式是不可以使用的,使用的话会抛出异常。

原因是使用第一种方式创建,Toast会自己创建一个view,即textview,而我们使用这个setText实际是向这个TextView设置内容,而自定义的View不会有这个控件,因此会报错。

原创粉丝点击