如何在按下设备上的后退按钮时完成listActivity

时间:2011-11-03 11:55:02

标签: android button listactivity back activity-finish

我使用以下代码完成一项活动,但我想在背压事件上完成列表活动。帮我 提前致谢

public void onBackPressed() {
         AlertDialog alertDialog = new AlertDialog.Builder(this).create();  
            alertDialog.setMessage("Want to exit ?");  
            alertDialog.setButton("Yes", new DialogInterface.OnClickListener() {  
              public void onClick(DialogInterface dialog, int which) { 
                  for(Activity activity:activities)
                       activity.finish();
            } });   
            alertDialog.setButton2("No", new DialogInterface.OnClickListener() {  
              public void onClick(DialogInterface dialog, int which) {  

            }});   
          alertDialog.show();  
    }

3 个答案:

答案 0 :(得分:0)

您的代码应修改如下..

@Override
    public void onBackPressed() {
        // TODO Auto-generated method stub

         AlertDialog alertDialog = new AlertDialog.Builder(this).create();  
         alertDialog.setMessage("Want to exit ?");  
         alertDialog.setButton("Yes", new DialogInterface.OnClickListener() {  
           public void onClick(DialogInterface dialog, int which) { 
              finish();
         } });   
         alertDialog.setButton2("No", new DialogInterface.OnClickListener() {  
           public void onClick(DialogInterface dialog, int which) {  

               return;
         }});   
       alertDialog.show(); 

    }

答案 1 :(得分:0)

我没有修改你的代码,只是我在这里建议新的代码,

public boolean onKeyDown(int keyCode, KeyEvent event) {
        // TODO Auto-generated method stub

        if(keyCode==KeyEvent.KEYCODE_BACK){
        new AlertDialog.Builder(ProgressController.this).setTitle(
        "Attention").setMessage(
        "Want to exit ?")
        .setPositiveButton("YES",
                new DialogInterface.OnClickListener() {
                    public void onClick(DialogInterface dialog,
                            int which) {
                        finish();
                    }
                }).setNegativeButton("NO",
                new DialogInterface.OnClickListener() {
                    public void onClick(DialogInterface dialog,
                            int which) {

                    }
                }).show();
        return true;
        }else{
            return false;
        }

        //return super.onKeyDown(keyCode, event);

    }

答案 2 :(得分:0)

在警报对话框中添加取消监听器,并从那里关闭您的活动。

    alertDialog.setCancelable(true);
    alertDialog.setOnCancelListener(new DialogInterface.OnCancelListener() {

        @Override
        public void onCancel(DialogInterface dialog) {
            finish();
        }
    });