PopupWindow定时关闭,点击外部或返回键关闭
Updated:
Contents
PopupWindow
定时关闭,点击外部或返回键关闭且取消定时任务
- 使用的是
Handler
的postDelayed
方式实现定时任务——关闭PopupWindow- 如果在定时任务执行之前,用户点击PopupWindow的
外部
或者back
键关闭了弹出窗口,
使用handler.removeCallbacks(r)
,从handler的消息队列中remove之前的runnable对象的回调
package com.lichen.niceslim.util;
import android.content.Context;
import android.graphics.drawable.BitmapDrawable;
import android.graphics.drawable.ColorDrawable;
import android.os.Handler;
import android.view.Gravity;
import android.view.LayoutInflater;
import android.view.View;
import android.view.WindowManager.LayoutParams;
import android.widget.PopupWindow;
import android.widget.TextView;
import com.lichen.niceslim.R;
public class QingQingPopup {
/**
* 普通显示PopupWindow
* @param context 上下文对象
* @param message 需要显示的信息
*/
public static void show(Context context, String message) {
View view = LayoutInflater.from(context).inflate(R.layout.dialog_toast, null);
final PopupWindow pop = new PopupWindow(view,
LayoutParams.WRAP_CONTENT, LayoutParams.WRAP_CONTENT, false);// 创建PopupWindow对象
TextView btn = (TextView) view.findViewById(R.id.toast_text);
pop.setBackgroundDrawable(new BitmapDrawable());//点击外边可消失
pop.setOutsideTouchable(true);//设置点击窗口外边窗口消失
pop.setFocusable(true);//设置此参数获得焦点,否则无法点击
btn.setText(message);
btn.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
if(pop.isShowing()) {
pop.dismiss();//隐藏窗口,如果设置了点击窗口外小时即不需要此方式隐藏
} else {
pop.showAsDropDown(v);//显示窗口
}
}
});
pop.showAtLocation(view, Gravity.CENTER, 0, 0);
}
/**
* 定时关闭的PopupWindow
* @param context 上下文对象
* @param message 需要显示的信息
*/
public static void showPopupWindowAutoDismiss(Context context, String message) {
View view = LayoutInflater.from(context).inflate(R.layout.dialog_toast, null);
final PopupWindow pop = new PopupWindow(view,
LayoutParams.WRAP_CONTENT, LayoutParams.WRAP_CONTENT, false);
TextView btn = (TextView) view.findViewById(R.id.toast_text);
btn.setText(message);
pop.setBackgroundDrawable(new ColorDrawable(android.R.color.transparent));//点击外边可消失
pop.setOutsideTouchable(true);//设置点击窗口外边窗口消失
pop.setFocusable(true);//设置此参数获得焦点,否则无法点击
final Runnable r = new Runnable() {
@Override
public void run() {
if(pop.isShowing()) {
pop.dismiss();
}
}
};
final Handler handler = new Handler();//使用Handler做定时关闭PopupWindow
pop.setOnDismissListener(new PopupWindow.OnDismissListener() {
@Override
public void onDismiss() {
/**如果定时任务到达前执行了关闭窗口,则取消定时任务。
此处是从handler的消息队列中remove之前的runnable对象的回调*/
handler.removeCallbacks(r);
}
});
pop.showAtLocation(view, Gravity.BOTTOM, 0, 0);
handler.postDelayed(r, 2000);//2秒后自动关闭
}
}