2015-10-19 131 views
0

我想通過按回顯按鈕來刪除該對話框,在對話框上顯示警報框。我在switch語句中創建了這個對話框。我嘗試了用一切可能的方面,但它並沒有幫助 繼承人我的代碼:通過按下後退按鈕在對話框上顯示警報框

lv.setOnItemClickListener(new OnItemClickListener() { 

      @Override 
      public void onItemClick(AdapterView<?> arg0, View arg1, int arg2, 
        long arg3) { 
       // TODO Auto-generated method stub 
       switch (arg2) { 
       case 0: 
        AlertDialog.Builder dialog = new AlertDialog.Builder(
          Listitem.this); 
        dialog.setTitle("kya h"); 
        dialog.setMessage("kuch ni"); 
        dialog.setCancelable(true); 
        dialog.create(); 
        dialog.show(); 

        dialog.setOnKeyListener(new OnKeyListener() { 

         @Override 
         public boolean onKey(DialogInterface dialog, 
           int keyCode, KeyEvent event) { 
          // TODO Auto-generated method stub 

          if (keyCode == KeyEvent.KEYCODE_BACK) { 
           // finish(); 
           // dialog.dismiss(); 
           exitByBackKey(); 
          } 
          return false; 
         } 

         private void exitByBackKey() { 
          // TODO Auto-generated method stub 
          AlertDialog.Builder alertbox = new AlertDialog.Builder(Listitem.this); 
          alertbox.setMessage("Do u want to exit"); 
          alertbox.setPositiveButton("Yes", 
            new DialogInterface.OnClickListener() { 

             @Override 
             public void onClick(
               DialogInterface dialog, 
               int which) { 
              // TODO Auto-generated 
              // method stub 
              finish(); 
              dialog.cancel(); 

             } 
            }) 
            .setNegativeButton(
              "No", 
              new DialogInterface.OnClickListener() { 

               @Override 
               public void onClick(
                 DialogInterface dialog, 
                 int which) { 
                // TODO Auto-generated 
                // method stub 

               } 
              }).show(); 

         } 
        }); 
        break; 

       } 
      } 
     }); 
    } 
} 

回答

0

要改變後退按鈕的行爲,所有你需要做的是重寫onBackPressed()方法。

@Override 
public void onBackPressed() { 
    new AlertDialog.Builder(this) 
     .setMessage("Do u want to exit") 
     .setNegativeButton("No") 
     .setPositiveButton("Yes", new OnClickListener() { 

      public void onClick(DialogInterface arg0, int arg1) { 
       finish(); 
       dialog.cancel(); 
      } 
     }).create().show(); 
} 

確保dialog是由onBackPressed()方法訪問。

相關問題