---
title: "Toast重复利用"
author: "uuubd"
date: "2013-04-26T00:10:53Z"
tags: []
categories: ["移动开发"]
slug: "toast"
draft: false
lastmod: "2013-04-26T00:08:40Z"
id: 1853869
url: "https://uuubd.iteye.com/blog/1853869"
---

```java
package com.example.toastdemo;

import android.app.Activity;
import android.os.Bundle;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.Button;
import android.widget.Toast;

public class ToastActivity extends Activity implements OnClickListener {
	private Toast toast;

    @Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.toast_main);
        Button hahaBtn = (Button) findViewById(R.id.hahaBtn);
        Button gagaBtn = (Button) findViewById(R.id.gagaBtn);
        hahaBtn.setOnClickListener(this);
        gagaBtn.setOnClickListener(this);
        
        //初始化一个Toast实例，之后重复利用
        toast = Toast.makeText(this, null, Toast.LENGTH_SHORT);
    }

	public void onClick(View v) {
		switch (v.getId()) {
		case R.id.hahaBtn:
			showMessage("哈哈");
			break;
		case R.id.gagaBtn:
			showMessage("嘎嘎嘎嘎嘎嘎嘎！！！");
			break;
		}
	}
	
	private void showMessage(String msg){
		/*
		 * 这里重复调用toast显示，系统会判断这个toast的id，如果队列中有这个
		 * toast，则将toast的显示的view和显示时长更新下（这里只是更新了文字）
		 * 重新显示，并重新计时。
		 * 主要是用在一些可能重复点击的地方，如果每次新建一个toast，则会将
		 * toast放到队列中，每个都会执行，当你点击很多次后，返回到别的页面，
		 * 依然会看到有之前点击产生的toast弹出，影响体验
		 */
		toast.setText(msg);
		toast.show();
	}
}

```


<span style="color:blue">toast_main.xml：</span>

```java
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    android:orientation="vertical" >

    <Button
        android:id="@+id/hahaBtn"
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:text="click me to show a 哈哈" />

    <Button
        android:id="@+id/gagaBtn"
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:text="click me to show 嘎嘎嘎" />

</LinearLayout>
```


运行顺序是点击第一个按钮显示"哈哈"，立马点击第二个按钮，能看到Toast的消息立刻变成“嘎嘎嘎嘎嘎嘎”，而且这次的toast的显示时间是重新计时的。

![](http://dl.iteye.com/upload/attachment/0083/6823/8bc15f44-c360-3e93-81b0-b2dbabdfd38d.png)

![](http://dl.iteye.com/upload/attachment/0083/6825/c41f57a7-0a25-35ff-ae75-2c50b08eaee3.png)


Toast和Notification差不多，用到的是一个类。都是将一个消息入队列，然后队列中的消息挨个显示。
Toast的cancel方法这里不推荐用，除非你想立即关闭这个Toast。试过，调用Toast::cancel，会将该Toast取消掉，但是有些机型还是会等待这个Toast的时间完毕后，才显示后续队列中的Toast。