最近项目较忙,没有时间去看书与写博客。这里分享下在项目中遇到的一引起典型的例子吧。
前面写了一篇防小米的自定义时间控件,也是在项目中遇到。上下效果图。这里使用popupWindow弹出控制,变灰的部分是popuwindow的背景。这里会遇到一个问题,在没点过确定时,返回键会失效。
这是为什么呢? 通过查阅,原因是这样, 全屏状态上popuwindw抢占了activity的焦点,而返回键是属于Activity的事件。所以无法被响应。
这里给出解决方案就是要想办法让popuwindow的控件去响应返回键,通常选择根布局。
1.该 Layout 的 Focusable 和 FocusableInTouchMode 都为 true。
2. 对该 View 重写 OnKeyListener() 事件。
下面给出弹出popuwindow的代码
/**
* 弹出时间选择对话框
*/
private void showDateDialog() {
View view = this.getLayoutInflater().inflate(R.layout.dialog_datetimepicker, null);
if (popupWindow == null) {
popupWindow = new PopupWindow(view, ViewGroup.LayoutParams.MATCH_PARENT,
ViewGroup.LayoutParams.MATCH_PARENT, true);
popupWindow.showAtLocation(view, Gravity.CENTER
| Gravity.CENTER, 0, 0);
popupWindow.setAnimationStyle(R.style.dialogAnimation);
ColorDrawable dw = new ColorDrawable(0x000000);
popupWindow.setBackgroundDrawable(dw);
popupWindow.update();
view.setOnKeyListener(new View.OnKeyListener() {
@Override
public boolean onKey(View v, int keyCode, KeyEvent event) {
if ((keyCode == KeyEvent.KEYCODE_BACK) && (popupWindow.isShowing())) {
popupWindow.dismiss();
return true;
}
return true;
}
});
popupWindow.setFocusable(true);
Button saveBtn = (Button) view.findViewById(R.id.saveBtn);
saveBtn.setOnClickListener(this);
datePicker = (MyDatePicker) view.findViewById(R.id.datePicker);
} else {
if (!popupWindow.isShowing()) {
popupWindow.showAtLocation(view, Gravity.RIGHT | Gravity.BOTTOM, 0, 0);
}
}
}