2013-08-31 239 views
0

我擰了一個簡單的腳本,其中有兩個選項的確認框。我需要在一次活動中多次調整它。所以我做了一個方法來做到這一點。基於返回的布爾值,我想寫出條件語句。Android alertdialogue返回布爾值

// Before oncreate 

    static boolean confirmation; 





    private void showConfirmation() { 
      // UserFunctions userFunctions = null; 
      // TODO Auto-generated methodastub 

      AlertDialog.Builder alertDialogBuilder = new AlertDialog.Builder(ProfileActivity.this); 

      // set title 
      alertDialogBuilder.setTitle("test"); 
      // set dialog message 
      alertDialogBuilder.setMessage("Please update the unfilled fields.").setCancelable(false) 
        .setPositiveButton("Ok", new DialogInterface.OnClickListener() { 
         @Override 
         public void onClick(DialogInterface dialog, int id) { 

          dialog.cancel(); 
          confirmation = false; 

         } 
        }).setNegativeButton("Later on", new DialogInterface.OnClickListener() { 
         @Override 
         public void onClick(DialogInterface dialog, int id) { 

          confirmation = true; 
         } 
        }); 

      // create alert dialog 
      AlertDialog alertDialog = alertDialogBuilder.create(); 

      // show it 
      alertDialog.show(); 

    }  








    @Override 
    public void myOnClickRecharge(View v) { 

     showConfirmation(); 
     if (confirmation){ 

     Intent intent = new Intent(getApplicationContext(), NewActivity.class); 
     startActivity(intent); 
     } 
    } 

回答

0

這樣你總是會返回false,因爲方法不會等待對話框關閉。我建議你使用一個靜態布爾值,並根據點擊的按鈕更改它的值。之前的onCreate():

boolean confirmation; 

然後在你的代碼:

alertDialogBuilder.setMessage("Please update the unfilled fields.").setCancelable(false) 
     .setPositiveButton("Ok", new DialogInterface.OnClickListener() { 
      @Override 
      public void onClick(DialogInterface dialog, int id) { 
       confirmation = false; 
       dialog.cancel(); 
      } 
     }).setNegativeButton("Later on", new DialogInterface.OnClickListener() { 
      @Override 
      public void onClick(DialogInterface dialog, int id) { 
        confirmation = true; 
      } 
     }); 

然後你檢查它的方式:

if (confirmation) 
{ 
    //Do something (TRUE) 
} 
else 
{ 
    //Do something (FALSE) 
} 

希望這有助於。祝你好運。

+0

編輯好了,請您檢查一下。 – user2534310

+0

但改變對話框按鈕內的什麼。改變它變得像礦。 –

+0

現在工作嗎?如果是的話,請註冊/選擇一個答案。 –