PopupWindow相比于Dialog框,PopupWindow是阻塞性的,Dialog框并不是阻塞性的。
PopupWindow定位布局比较方便,可以居于某个布局的下面。位子比较好控制。但是Dialog需要靠像素来调整。而且PopupWindow显隐比较方便,不用你进行判断。如果已经显示,则直接进行隐藏。
下面贴出PopupWindow的代码:
LayoutInflater inflater = (LayoutInflater) getSystemService(Context.LAYOUT_INFLATER_SERVICE);
View view = inflater.inflate(R.layout.title_select_layout, null);
//从dimen文件中获取固定尺寸
float width=MyApp.getInstance().getResources().getDimension(R.dimen.select_dialog);
PopupWindow window = new PopupWindow(view,(int)width, WindowManager.LayoutParams.WRAP_CONTENT);
//设置背景透明度
WindowManager.LayoutParams lp = getWindow().getAttributes();
lp.alpha = 0; //0.0-1.0
getWindow().setAttributes(lp);
// 设置popWindow弹出窗体可点击,这句话必须添加,并且是true
window.setFocusable(true);
window.setOutsideTouchable(true);
window.update();
window.setBackgroundDrawable(new BitmapDrawable());
//上述4个方法必须放在showAtLocation()方法之前,点击空白部分隐藏的功能才能起作用
//以下的方法就是设置布局的位置,可以设置在某个布局的下方的多少的距离
window.showAsDropDown(findViewById(R.id.find_title), 0, 0);
设置Dialog的框的代码也贴一下:
AlertDialog.Builder taskDialog = new Dialog(mContext, R.style.my_dialog);
View v = LayoutInflater.from(mContext).inflate(
R.layout.face_dialog_layout, null);
taskDialog.setContentView(v);
v.measure(View.MeasureSpec.UNSPECIFIED, View.MeasureSpec.UNSPECIFIED);
GridView gv_face= (GridView)v.findViewById(R.id.gv_face);
taskDialog.setCancelable(true);
taskDialog.setCanceledOnTouchOutside(true);
Window dwindow = taskDialog.getWindow();
dwindow.setWindowAnimations(R.style.dialogstyle); // 设置窗口弹出动画
WindowManager.LayoutParams wl = dwindow.getAttributes();
wl.dimAmount =0f;
// 根据x,y坐标设置窗口需要显示的位置
DisplayMetrics metric = new DisplayMetrics();
getWindowManager().getDefaultDisplay().getMetrics(metric);
//此处设置布局的位置
wl.x = metric.widthPixels / 2 ;
wl.y = metric.heightPixels;
adapter = new FaceAdapter(mContext, et_content, facelist,gv_face);
gv_face.setAdapter(adapter);
float keyboardHeight = getResources().getDimension(
R.dimen.keyboard_height);
taskDialog.getWindow().setLayout(RelativeLayout.LayoutParams.MATCH_PARENT, (int) keyboardHeight);
//以下的监听注册事件可以注释掉
taskDialog.setOnDismissListener(new DialogInterface.OnDismissListener() {
@Override
public void onDismiss(DialogInterface dialogInterface){
//Dialog框消失的时候需要触发的事件
}
});
taskDialog.show();
这里提一下Dialog框的dismiss()方法以及cancel方法区别。
首先呢, AlertDialog继承与Dialog。
然后呢,在Dialog类中找到了dismiss和cancel方法的实现。先看看dismiss的源码:
public void cancel() {
if (mCancelMessage != null) {
// Obtain a new message so this dialog can be re-used
Message.obtain(mCancelMessage).sendToTarget();
}
dismiss();
}
public void setOnCancelListener(final OnCancelListener listener) {
if (listener != null) {
mCancelMessage = mListenersHandler.obtainMessage(CANCEL, listener);
} else {
mCancelMessage = null;
}
}
ublic void setCancelMessage(final Message msg) {
mCancelMessage = msg;
}
在cancel方法中调用了dismiss方法。也就是说mCancelMessage变量你不让他起作用,则cancel等同于dismiss。