安德鲁斯Toast它们的定义和防止重复显示器

     Toast安卓系统,当用户错误或功能运行完成,提示,要求用户,它不集中,并且将在一定时间内消失。然而,在用户继续误(如登录,password错)当次,将有多个Toast创建。系统会把这些toast放进队列中,等待上个Toast 显示完成。接着显示下一个。那么用户则会看到多次Toast提示,不管你退出软件与否,这样给用户的体验则大打折扣。所以我们须要做的是,若Toast已在显示(也就是Toast!=null)时,就不用再又一次new了。直接setText要显示的信息就可以,仅仅有Toast为空时,才又一次new。分析到这里,大家应该明确怎么去写了吧。第二个问题是,为了使Toast能跟我们自己的应用风格搭配。经常须要我们自己定义Toast显示。接下来。我们就来解决这两个问题:

    既然为自己定义,则经常会有个自己定义布局,并增加自己定义背景——custom_toast.xml:


接下来看主代码:

import android.content.Context;
import android.os.Handler;
import android.view.Gravity;
import android.view.LayoutInflater;
import android.view.View;
import android.widget.TextView;
import android.widget.Toast;

/**
 * 
 * @author byl
 */
public class ToastUtil {
	
	private static Toast mToast;
	
	   private static Handler mHandler = new Handler();
	    private static Runnable r = new Runnable() {
	        public void run() {
	            mToast.cancel();
	            mToast=null;//toast隐藏后,将其置为null
	        }
	    };
	
	public static void showShortToast(Context context, String message) {
		LayoutInflater inflater = (LayoutInflater) context.getSystemService(Context.LAYOUT_INFLATER_SERVICE);
		View view = inflater.inflate(R.layout.custom_toast, null);//自己定义布局
		TextView text = (TextView) view.findViewById(R.id.toast_message);//显示的提示文字
		text.setText(message);
		mHandler.removeCallbacks(r);
        if (mToast == null){//仅仅有mToast==null时才又一次创建,否则仅仅需更改提示文字
        	mToast = new Toast(context);
    		mToast.setDuration(Toast.LENGTH_SHORT);
    		mToast.setGravity(Gravity.BOTTOM, 0, 150);
    		mToast.setView(view);
        }
        mHandler.postDelayed(r, 1000);//延迟1秒隐藏toast
		mToast.show();
}
}


使用时,直接调用showShortToast()方法就可以。如:ToastUtil.showShortToast(this,"password不能为空"),


效果会是这种:

安德鲁斯Toast它们的定义和防止重复显示器

版权声明:本文博客原创文章,博客,未经同意,不得转载。