自定義Toast及視窗透明處理

仙劍情緣發表於2018-01-28
public class ToastUtils {

    public static void ToastDialog(final Activity context,int resId) {
        Toast toast = new Toast(context);
        toast.setGravity(Gravity.CENTER, 0, 0);
        toast.setDuration(Toast.LENGTH_SHORT);
        View view = LayoutInflater.from(context).inflate(resId, null);
        WindowManager wm = context.getWindowManager();
        Point point = new Point();
        wm.getDefaultDisplay().getSize(point);
        int w = point.x * 3 / 4;
        toast.setView(view);
        adjustViewBrightness(view, context);
        toast.show();
    }

    public static void adjustViewBrightness(View view, final Activity context) {
        final WindowManager.LayoutParams lp = context.getWindow().getAttributes();
        lp.alpha = 0.8f;
        context.getWindow().setAttributes(lp);
        context.getWindow().addFlags(WindowManager.LayoutParams.FLAG_DIM_BEHIND);

        view.addOnAttachStateChangeListener(new View.OnAttachStateChangeListener() {
            @Override
            public void onViewAttachedToWindow(View view) {

            }

            @Override
            public void onViewDetachedFromWindow(View view) {
                lp.alpha = 1.0f;
                context.getWindow().clearFlags(WindowManager.LayoutParams.FLAG_DIM_BEHIND);
                context.getWindow().setAttributes(lp);
            }
        });
    }

}

相關文章