Android 自定义Dialog,以及失去焦点之后,Dialog消失的解决

自己参照网上的大量自定义Dialog的方法,也写出了在项目中使用的自定义Dialog,下面是实现代码:

/**
 * 自定义进度条Dialog
 * @author Administrator
 *
 */
public class CustomProgressDialog extends Dialog {
	private static CustomProgressDialog mCustomProgressDialog = null;

	public CustomProgressDialog(Context context) {
		super(context);
	}

	public CustomProgressDialog(Context context, int theme) {
		super(context, theme);
	}

	public static CustomProgressDialog createDialog(Context context) {
		return createDialog(context, false);
	}

	public static CustomProgressDialog createDialog(Context context,
			boolean cancel) {
		mCustomProgressDialog = new CustomProgressDialog(context,
				R.style.CustomProgressDialog);
		mCustomProgressDialog.setContentView(R.layout.custom_progress_dialog);
		mCustomProgressDialog.getWindow().getAttributes().gravity = Gravity.CENTER;

		ImageView loadingProfress = (ImageView) mCustomProgressDialog
				.findViewById(R.id.loading_progress);
		Animation animation = AnimationUtils.loadAnimation(context,
				R.anim.loading_progress_animation);
		loadingProfress.setAnimation(animation);
		mCustomProgressDialog.setCancelable(cancel);// 是否可以用“返回键”取消
		return mCustomProgressDialog;
	}

	@Override
	public void onWindowFocusChanged(boolean hasFocus) {
		if (mCustomProgressDialog == null) {
			return;
		}
		if (!hasFocus) {
			dismiss();
		}
	}

}
这个是Dialog需要用到的布局文件:




    

    

还有进度条的动画效果:



    

上面,已经把自定义Dialog实现的全部代码粘贴出来了,但是在使用过程中,出现了一个bug,在下面会进行详细说明。。。

----------------------------------

但是,上面的实现,在实际的使用过程,出现了这么一个情况,当你将顶部的状态栏下拉时,Dialog会消失,这是一个什么情况咧?

嘻嘻,因为在代码中,我重写了这么一个方法

@Override
	public void onWindowFocusChanged(boolean hasFocus) {
		if (mCustomProgressDialog == null) {
			return;
		}
		if (!hasFocus) {
			dismiss();
		}
	}
onWindowFocusChanged(boolean hasFocus) :当Dialog获取焦点,或者失去焦点时,这个方法都会被调用,也就是当前界面焦点发生改变时,这个方法就会运行
看一看看我重写的这个方法里面的实现,当失去焦点时,hasFocus == false , 会dismiss掉这个Dialog。
问题得到了解决,
因为重写了onWindowFocusChanged方法,里面的实现导致Dialog失去焦点后,dismiss掉。。。。我忘记了当时,为什么要重写这个方法了。。。
那么这个问题怎么解决,不用我说了吧。。。
//	@Override
//	public void onWindowFocusChanged(boolean hasFocus) {
//		if (mCustomProgressDialog == null) {
//			return;
//		}
//		if (!hasFocus) {
//			dismiss();
//		}
//	}
注释掉就行了。。。

行了,解释完毕。

代码天然无污染,可放心食用。。。。




你可能感兴趣的:(Android)