我有一个活动,一打开就打开一个Dialog:
/** Called when the activity is first created. */
@Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
mPath = new File(getIntent().getExtras().getString("START_PATH"));
FTYPE = getIntent().getExtras().getString("FILTER");
showDialog(DIALOG_LOAD_FILE);
}
我试图在用户单击后退按钮(同时仍在Dialog中)时这样做,退出整个活动。我有以下内容:
@Override
public boolean onKeyDown(int keyCode, KeyEvent event) {
if (keyCode == KeyEvent.KEYCODE_BACK) {
Intent resultIntent = new Intent();
resultIntent.putExtra("FILE_PATH", mPath.toString());
setResult(Activity.RESULT_OK, resultIntent);
finish();
}
return true;
}
如果对话框不再存在,则此方法很有用,但如果对话框仍处于活动状态,则不会被调用。想法?
答案 0 :(得分:1)
在实例化onKeyDown()
时,您是否尝试在Dialog
类中覆盖Dialog
?我没有测试过,但尝试类似
@Override
protected void onCreateDialog(int id) {
Dialog dialog = null;
switch(id) {
case DIALOG_LOAD_FILE:
dialog = new AlertDialog(mContext) {
@Override
public boolean onKeyDown(int keyCode, KeyEvent event) {
if(keyCode == KeyEvent.KEYCODE_BACK) {
dismiss();
finish();
return true;
}
return super.onKeyDown(keyCode, event);
}
};
break;
}
return dialog;
}
答案 1 :(得分:1)
您必须创建DialogInterface.OnKeyListener
的对象,并且可以覆盖onKey(DialogInterface dialog, int keyCode, KeyEvent event)
。此方法捕获对话框内的键事件。
例如:
AlertDialog.Builder dialogBuilder = new AlertDialog.Builder(this);
//do something to your dialog like: dialogBuilder.setView(view);
DialogKeyListener dkl = new DialogKeyListener();
dialogBuilder.setOnKeyListener(dkl);
AlertDialog dialog = dialogBuilder.create();
dialog.show();
和监听器类:
private class DialogKeyListener implements android.content.DialogInterface.OnKeyListener
{
@Override
public boolean onKey(DialogInterface dialog, int keyCode, KeyEvent event)
{
if(keyCode == KeyEvent.KEYCODE_BACK)
{
dialog.dismiss();
yourClassActivity.finish(); // or something like that
return false;
}
return true
}
}
答案 2 :(得分:1)
试试这个
AlertDialog.Builder alertDialogBuilder = new AlertDialog.Builder(
this);
// set prompts.xml to alertdialog builder
alertDialogBuilder.setView(promptsView);
alertDialogBuilder
.setCancelable(true);
// create alert dialog
final AlertDialog dialogDiscount = alertDialogBuilder.create();
// show it
dialogDiscount.show();
OnKeyListener keylistener = new OnKeyListener() {
@Override
public boolean onKey(DialogInterface dialog, int keyCode, KeyEvent KEvent) {
int keyaction = KEvent.getAction();
if(keyaction == KeyEvent.ACTION_DOWN)
{
int keycode = KEvent.getKeyCode();
int keyunicode = KEvent.getUnicodeChar(KEvent.getMetaState() );
char character = (char) keyunicode;
if(keycode==KeyCode.Enter){
}
}
return false;
}
};
dialogDiscount.setOnKeyListener(keylistener );
答案 3 :(得分:0)
AlertDialog alertDialog = new AlertDialog.Builder(this).create();
alertDialog.setTitle("your title");
alertDialog.setMessage("your message");
alertDialog.setOnCancelListener(new OnCancelListener() {
@Override
public void onCancel(DialogInterface dialog) {
dialog.dismiss();
finish();
}
});
alertDialog.show();