在项目开发中,经常会遇到各种通过弹框提示信息的需求,主要都是通过Dialog或者PopupWindow,由于在项目中可能需要多次用到,于是自己重写了2个类方便随时调用。
自定义Dialog类:
public abstract class CustomBaseDialog extends Dialog implements自定义 PopupWindow 类:
android.view.View.OnClickListener {
/**
* 布局文件
*/
public int layoutResID;
public CustomBaseDialog(Context context, int layoutResID) {
super(context);
this.layoutResID = layoutResID;
}
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
getWindow().setBackgroundDrawableResource(android.R.color.transparent);
requestWindowFeature(Window.FEATURE_NO_TITLE);
setContentView(layoutResID);
setCanceledOnTouchOutside(false);
Window w = getWindow();
w.setWindowAnimations(R.style.PopupAnimation);
init();
}
/**
* @author xc
* @date 2016-3-31 下午2:43:15
* @describe 初始化控件和填充数据
*/
public abstract void init();
}
public abstract class CustomBasePopupWindow extends PopupWindow{
/**
* 布局文件
*/
private PopupWindow mPreviewPopup;
private View view;
/**
* @param context 上下文
* @param layoutResID 布局文件
* @param width 窗口宽度
* @param height 窗口高度
*/
public CustomBasePopupWindow(Context context, int layoutResID, int width, int height) {
mPreviewPopup = new PopupWindow(context);
view = LayoutInflater.from(context).inflate(layoutResID, null);
mPreviewPopup.setWidth(width);
mPreviewPopup.setHeight(height);
mPreviewPopup.setContentView(view);
mPreviewPopup.setBackgroundDrawable(new ColorDrawable(0x00000000));
}
/**
* @param x 显示位置所在x坐标
* @param y 显示位置所在y坐标
*/
public void show(int x, int y) {
mPreviewPopup.showAtLocation(view, Gravity.NO_GRAVITY, x, y);
}
/**
* 关闭
*/
public void dismiss() {
if (mPreviewPopup != null) {
mPreviewPopup.dismiss();
}
}
/**
* 当点击外部不消失窗口,并且能相应外部控件的点击事件
*/
public void setPopupWindowTouchModal(boolean touchModal) {
if (null == mPreviewPopup) {
return;
}
Method method;
try {
method = PopupWindow.class.getDeclaredMethod("setTouchModal", boolean.class);
method.setAccessible(true);
method.invoke(mPreviewPopup, touchModal);
} catch (Exception e) {
e.printStackTrace();
}
}
/**
* @author xc
* @date 2016-3-31 下午2:43:15
* @describe 初始化需要更新数据或者处理点击事件的控件
*/
public abstract void init();
}