自定义消息提醒

版权声明:本文为博主原创文章,未经博主允许不得转载。 https://blog.csdn.net/wei11556/article/details/83273873
package com.lisn.demo181010.View;

import android.content.Context;
import android.os.Handler;
import android.util.Log;
import android.view.Gravity;
import android.view.LayoutInflater;
import android.view.View;
import android.view.WindowManager;
import android.widget.TextView;

import com.lisn.demo181010.R;


public class MyMsgBox {

    private int HIDE_DELAY = 5000;
    private int gravity = Gravity.CENTER;
    private TextView mTextView;
    private Handler mHandler;

    private WindowManager.LayoutParams wmParams = new WindowManager.LayoutParams();
    private WindowManager wManager;
    private final View v;

    private Context mContext;

    /**
     * @param context
     * @param HIDE_DELAY  显示时间
     * @param gravity     Gravity.BOTTOM | Gravity.CENTER;
     *                    Gravity.TOP 、 Gravity.LEFT 、 Gravity.RIGHT
     */
    public MyMsgBox(Context context, int HIDE_DELAY, int gravity) {
        LayoutInflater inflater = LayoutInflater.from(context);
        //获取浮动窗口视图所在布局
        v = inflater.inflate(R.layout.newmb_messagebar, null);

        this.HIDE_DELAY = HIDE_DELAY;
        this.gravity = gravity;
        this.mContext = context;
        init(v);
    }

    private void init(final View v) {
        mTextView = (TextView) v.findViewById(R.id.mbMessage);
        mHandler = new Handler();
    }

    public void show(String message) {
        wManager = (WindowManager) mContext.getApplicationContext().getSystemService(Context.WINDOW_SERVICE);
        wmParams.type = WindowManager.LayoutParams.TYPE_TOAST; // 设置window type
        wmParams.flags = WindowManager.LayoutParams.FLAG_NOT_FOCUSABLE;
        wmParams.gravity = this.gravity;
        wmParams.width = WindowManager.LayoutParams.WRAP_CONTENT;
        wmParams.height = WindowManager.LayoutParams.WRAP_CONTENT;
        // 以屏幕左上角为原点,设置x、y初始值,相对于gravity
        wmParams.x = 0;    //位置偏移量
        wmParams.y = 100;  //位置偏移量
        mTextView.setText(message);
        try {
            wManager.addView(v, wmParams);
        } catch (Exception e) {
            Log.e("---------", e.toString());
            Log.e("---------", e.toString());
        }
        mHandler.postDelayed(mHideRunnable, HIDE_DELAY);
    }

    private final Runnable mHideRunnable = new Runnable() {
        @Override
        public void run() {
            wManager.removeView(v);
        }
    };

}

猜你喜欢

转载自blog.csdn.net/wei11556/article/details/83273873