大神们,快来看看这个神奇的问题吧!!
我在Activity弹出一个PopupWindow,PopupWindow上有一个EditText,如果我不去触碰它,我点击返回键可以把PopupWindow关闭,但是我一旦点了输入框,弹出软键盘,那这时我再怎么点返回键都没用,都关不了PopupWindow。以下是我的代码:
事件被分发到edittext了,为edittext 设置onKeyListener即可,可以参照一下以下代码。
import android.app.Activity;
import android.os.Bundle;
import android.view.Gravity;
import android.view.KeyEvent;
import android.view.LayoutInflater;
import android.view.View;
import android.view.View.OnClickListener;
import android.view.View.OnKeyListener;
import android.view.WindowManager;
import android.widget.Button;
import android.widget.EditText;
import android.widget.PopupWindow;
public class PopUpWindowTestActivity extends Activity {
private Button btnPopup;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_pop_up_window_test);
btnPopup = (Button) findViewById(R.id.btn_popup);
btnPopup.setOnClickListener(new OnClickListener() {
@Override
public void onClick(View v) {
showPopupWindow(v);
}
});
}
private MPopupWindow popupWindow = null;
protected void showPopupWindow(View v) {
if (popupWindow == null)
popupWindow = new MPopupWindow(this, 500, 300);
popupWindow.show(v);
}
class MPopupWindow extends PopupWindow {
private final Activity mContext;
private View contentView;
public MPopupWindow(Activity ctx, int width, int height) {
super(width, height);
this.mContext = ctx;
contentView = LayoutInflater.from(mContext).inflate(
R.layout.popup_content, null);
init();
}
private EditText txtTest;
private void init() {
txtTest = (EditText) contentView.findViewById(R.id.editText1);
contentView.setFocusable(true);
contentView.setFocusableInTouchMode(true);
this.setFocusable(true);
this.setOutsideTouchable(true);
this.setContentView(contentView);
this.setInputMethodMode(PopupWindow.INPUT_METHOD_FROM_FOCUSABLE);
this.setSoftInputMode(WindowManager.LayoutParams.SOFT_INPUT_ADJUST_PAN);
txtTest.setOnKeyListener(new OnKeyListener() {
@Override
public boolean onKey(View v, int keyCode, KeyEvent event) {
// TODO Auto-generated method stub
if (keyCode == KeyEvent.KEYCODE_BACK) {
dismiss();
return true;
}
return false;
}
});
}
public void show(View parent) {
this.setBackgroundAplha(0.4f);
this.showAtLocation(parent, Gravity.CENTER, 0, 0);
}
@Override
public void dismiss() {
setBackgroundAplha(1.0f);
super.dismiss();
}
private void setBackgroundAplha(float alpha) {
WindowManager.LayoutParams lp = mContext.getWindow()
.getAttributes();
lp.alpha = alpha;
mContext.getWindow().setAttributes(lp);
}
}
}
版权声明:本文内容由阿里云实名注册用户自发贡献,版权归原作者所有,阿里云开发者社区不拥有其著作权,亦不承担相应法律责任。具体规则请查看《阿里云开发者社区用户服务协议》和《阿里云开发者社区知识产权保护指引》。如果您发现本社区中有涉嫌抄袭的内容,填写侵权投诉表单进行举报,一经查实,本社区将立刻删除涉嫌侵权内容。