处理AlertDialog.Builder中的后退按钮

时间:2014-07-28 11:01:01

标签: android alertdialog

当我按下后退按钮,显示dilog构建器时,我想完成()应用程序。

我有以下代码

private void displaydialog() 
{
    final LayoutInflater inflator = LayoutInflater.from(this);
    final View settingsview = inflator.inflate(R.layout.nointernet, null);
    final AlertDialog.Builder builder = new AlertDialog.Builder(this);

    builder.setIcon(R.drawable.reminderalert);
    builder.setTitle("No Network...");
    builder.setView(settingsview);

    builder.setPositiveButton(android.R.string.ok, new DialogInterface.OnClickListener() 
    {
        @Override
        public void onClick(DialogInterface dialog, int which) 
        {
            startActivity(new Intent(android.provider.Settings.ACTION_SETTINGS));
            dialog.dismiss();
        }
    });

    builder.create().show();
}

我不确定在哪里插入OnKeylistener和Key事件。有人可以指导我何时/如何插入监听器?

谢谢!

3 个答案:

答案 0 :(得分:7)

如果要在点击Activity Negative Button或点击硬件后退按钮(显示AlertDialog时)时完成当前AlertDialog然后做类似下面的事情,

pDialog.setOnCancelListener(new DialogInterface.OnCancelListener() {
            @Override
            public void onCancel(DialogInterface dialog) {
                // if from activity
                finish();

            }

        });

答案 1 :(得分:0)

设置onBackPressed();并在该调用中onBackPressed() ..

builder.setNegativeButton(R.string.cancel, new DialogInterface.OnClickListener() {
       public void onClick(DialogInterface dialog, int id) {
           // User cancelled the dialog
onBackPressed();
       }
   });


 @Override
public void onBackPressed() {
     finish();
 }

答案 2 :(得分:0)

用这个...... 按回按钮时,此方法处理完成当前活动

@Override
public boolean onKeyDown(int keyCode, KeyEvent event) {

    if (keyCode == KeyEvent.KEYCODE_BACK) {

        finish();

        return true;
    } else {

    }
}