静态Toast

2018-07-13  本文已影响9人  奋斗滴猩猩
1.为什么使用静态toast

直接使用系统的toast,如果想要多弹几个,需要排队弹出,用户体验不好;

2.使用
// 在activity中button弹出toast
// 使用getApplicationContext(),是防止activity的内存泄露
findViewById(R.id.toast1).setOnClickListener(new View.OnClickListener() {
 @Override
public void onClick(View v) {               ToastUtil.getInstance(getApplicationContext()).showSToast("小姐姐");       
   }
//静态toast类
public class ToastUtil {
    private static ToastUtil mToastUtil;
    private static Toast mToast;
    private ToastUtil (Context context) {
        if (mToast == null) {
            mToast = Toast.makeText(context, "", Toast.LENGTH_SHORT);
        }
    }
// 确保toast对象只有一个
    public static synchronized ToastUtil getInstance(Context context) {
        if (mToastUtil == null) {
            synchronized (ToastUtil.class) {
                if (mToastUtil == null) {
                    mToastUtil = new ToastUtil(context);
                }
            }
        }
        return mToastUtil;
    }
// 弹出短时间toast
    public void showSToast(String msg) {
        if (mToast == null) {
            return;
        }
        mToast.setText(msg);
        mToast.setDuration(Toast.LENGTH_SHORT);
        mToast.show();
    }
// 弹出长时间toast
    public void showLToast(String msg) {
        if (mToast == null) {
            return;
        }
        mToast.setText(msg);
        mToast.setDuration(Toast.LENGTH_LONG);
        mToast.show();
    }
}


上一篇 下一篇

猜你喜欢

热点阅读