自定义Toast(解决小米手机或用户关闭通知不显示)

public class Toast {

private Context mContext;
private WindowManager wm;
private int mDuration;
private View mNextView;
public static final int LENGTH_SHORT = 1500;
public static final int LENGTH_LONG = 3000;

public Toast(Context context) {
    mContext = context.getApplicationContext();
    wm = (WindowManager) mContext.getSystemService(Context.WINDOW_SERVICE);
}

public static Toast makeText(Context context, CharSequence text,
        int duration) {
    Toast result = new Toast(context);
    LayoutInflater inflate = (LayoutInflater) context
            .getApplicationContext().getSystemService(
                    Context.LAYOUT_INFLATER_SERVICE);
    View v = inflate.inflate(R.layout.common_toast, null);
    TextView tv = (TextView) v.findViewById(R.id.toast_text);
    tv.setText(text);
    result.mNextView = v;
    result.mDuration = duration;
    return result;
}

public static Toast makeText(Context context, int resId, int duration)
        throws Resources.NotFoundException {
    return makeText(context, context.getResources().getText(resId),duration);
}

public void show() {
    if (mNextView != null) {
        WindowManager.LayoutParams params = new WindowManager.LayoutParams();
        params.gravity = Gravity.CENTER | Gravity.CENTER_HORIZONTAL;
        params.height = WindowManager.LayoutParams.WRAP_CONTENT;
        params.width = WindowManager.LayoutParams.WRAP_CONTENT;
        params.flags = WindowManager.LayoutParams.FLAG_NOT_FOCUSABLE
                | WindowManager.LayoutParams.FLAG_NOT_TOUCHABLE
                | WindowManager.LayoutParams.FLAG_KEEP_SCREEN_ON;
        params.format = PixelFormat.TRANSLUCENT;
        params.windowAnimations = R.style.Animation_Toast;
        params.y = dip2px(mContext, 64);
        params.type = WindowManager.LayoutParams.TYPE_TOAST;
        wm.addView(mNextView, params);
        new Handler().postDelayed(new Runnable() {

            @Override
            public void run() {
                if (mNextView != null) {
                    wm.removeView(mNextView);
                    mNextView = null;
                    wm = null;
                }
            }
        }, mDuration);
    }
}

/**
  * dip与px的转换
  *
  * @参数   @param context
  * @参数   @param dipValue
  * @返回值 int
  *
 */
private int dip2px(Context context, float dipValue) {
    final float scale = context.getResources().getDisplayMetrics().density;
    return (int) (dipValue * scale + 0.5f);
}
评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值