2 xiaoyan 12 xiaoyan_12 于 2012.11.28 13:25 提问

按手机的返回键结束listActivity

我使用以下代码来结束一个activity的运行。但是我想使用BackPress事件来结束list activity。这个方法怎么实现,能在我原代码上改吗,请求大家帮忙!

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个回答

LiDaming_and
LiDaming_and   2012.11.28 14:47
已采纳

我没有改你的代码,这是我的代码,请你参考:

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);

    }
nana4ever
nana4ever   2012.11.28 15:25

你的代码可以改成这样:

@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(); 

    }
CSDN_Ask
CSDN_Ask   2012.11.28 17:26

在对话框中添加一个监听器到取消,并在那里关闭你的activity。

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

        @Override
        public void onCancel(DialogInterface dialog) {
            finish();
        }
    });
Csdn user default icon
上传中...
上传图片
插入图片
准确详细的回答,更有利于被提问者采纳,从而获得C币。复制、灌水、广告等回答会被删除,是时候展现真正的技术了!