2011-06-09 95 views
3

由于回退键销毁我的应用程序,所有数据都将丢失我需要拦截它以询问用户是否真的是他想要的。Android:拦截回密钥

我以为以下结构:

@Override 
    public boolean onKeyDown(int keyCode, KeyEvent event) 
    {  
     if (keyCode == KeyEvent.KEYCODE_BACK && event.getRepeatCount() == 0) 
     { 
     // ask user if he really wants to exit 
     // no --> return true; 
     // yes --> return super.onKeyDown(keyCode, event); 
     //manually entering either of the return values works fine 
     } 
    return super.onKeyDown(keyCode, event); 
    } 

的“询问用户”的一块,我想用一个警告对话框来实现。我的问题是,现在显示的是警告对话框,但onKeyDown方法在显示警告对话框时运行到最后,并且在警告对话框中,我不知道如何告诉系统传递正确的返回值。

完整的代码,我脑子里想的是

@Override 
    public boolean onKeyDown(int keyCode, KeyEvent event) 
    {  
     if (keyCode == KeyEvent.KEYCODE_BACK && event.getRepeatCount() == 0) 
     { 

      alertDialog = new AlertDialog.Builder(this).create(); 
      alertDialog.setTitle("Tile"); 
      alertDialog.setMessage("data lost, are you sure?"); 

      alertDialog.setButton(-1, getString(R.string.yes), new DialogInterface.OnClickListener() 
      { 
       @Override 
       public void onClick(DialogInterface dialog, int which) 
       { 
        return; 
        //I only can return without a boolean value here.     } 
      }); 

      alertDialog.setButton(-2, getString(R.string.no), new DialogInterface.OnClickListener() 
      { 
       @Override 
       public void onClick(DialogInterface dialog, int which) 
       { 
        return; 
       } 
      }); 

      alertDialog.show(); 
     } 
     return super.onKeyDown(keyCode, event); 
    } 

感谢,A

+0

删除回报super.onKeyDown(的keyCode,事件); – motoku 2011-06-09 07:58:18

回答

3

当用户按下后,出现对话框。

onKeyDown现在已经处理,所以你返回true。

现在你的对话框显示,

当您按下是你想模仿后退按钮是什么finish();确实

当您按下没有你只是关闭对话框,并在活动继续

你会想这样的:

@Override 
public boolean onKeyDown(int keyCode, KeyEvent event) 
{  
    if (keyCode == KeyEvent.KEYCODE_BACK && event.getRepeatCount() == 0) 
    { 

     alertDialog = new AlertDialog.Builder(this).create(); 
     alertDialog.setTitle("Tile"); 
     alertDialog.setMessage("data lost, are you sure?"); 

     alertDialog.setButton(-1, getString(R.string.yes), new DialogInterface.OnClickListener() 
     { 
      @Override 
      public void onClick(DialogInterface dialog, int which) 
      { 
       finish(); // or yourContext.finish(); 
       //I only can return without a boolean value here.     
      } 
     }); 

     alertDialog.setButton(-2, getString(R.string.no), new DialogInterface.OnClickListener() 
     { 
      @Override 
      public void onClick(DialogInterface dialog, int which) 
      { 
       // do nothing dialog will dismiss 
      } 
     }); 

     alertDialog.show(); 
     return true; //meaning you've dealt with the keyevent 
    } 
    return super.onKeyDown(keyCode, event); 
} 
0

alertDialog.show();应该在没有按钮的情况下调用