问题描述
我有这个对话框,只有一个 textView 而没有按钮。它显示了一些信息,我需要更改左右按键的信息。不幸的是,对话框在任意键上关闭。 MainActivity中的这段代码调用对话框(冗余代码省略)
@Override
public boolean dispatchKeyEvent(KeyEvent event) {
if (event.getKeyCode() == KeyEvent.KEYCODE_MENU) {
if (event.getAction() == KeyEvent.ACTION_UP) {
InfoDialog infoDialog = new InfoDialog();
infoDialog.showDialog(this,currentDateAndTime,chn);
return true;
}
}
return super.dispatchKeyEvent(event);
}
这是对话框代码
public class InfoDialog {
private int counter = 0;
private Dialog dialog;
public void showDialog(final Activity activity,final String DateTime,final ChannelList.Channel chn){
dialog = new Dialog(activity);
dialog.requestwindowFeature(Window.FEATURE_NO_TITLE);
dialog.setCancelable(false);
dialog.setContentView(R.layout.info_dialog);
counter = 0;
setDialogText(chn,DateTime,counter);
dialog.setonKeyListener(new DialogInterface.OnKeyListener() {
@Override
public boolean onKey(DialogInterface dialogInterface,int i,KeyEvent keyEvent) {
if (keyEvent.getKeyCode() == KeyEvent.KEYCODE_DPAD_LEFT) {
if (keyEvent.getAction() == KeyEvent.ACTION_UP) {
if (counter>0) counter--;
setDialogText(chn,counter);
return true;
}
}
if (keyEvent.getKeyCode() == KeyEvent.KEYCODE_DPAD_RIGHT) {
if (keyEvent.getAction() == KeyEvent.ACTION_UP) {
if (counter<chn.infoText.size()-1) counter++;
setDialogText(chn,counter);
return true;
}
}
dialog.dismiss();
return false;
}
});
dialog.show();
}
}
当我按下任何按钮时,对话框关闭,即使 onKey 已被调用。 我错过了什么?如何仅处理对话框的按键? (其他对话框可能使用相同的键进行不同的操作)
解决方法
好吧,在 InfoDialog
中,您正在设置 DialogInterface.OnKeyListener
并在 onKey
方法的底部调用 dialog.dismiss()
,尝试删除此行...(还有return true
任何情况)