2011-11-18 51 views
1

我在設置警報對話框中的默認選定項目時遇到了一些問題。以下是我在我的代碼中使用:android獲取警報對話框默認選定項目

if(memory>megAvailable){ 
     selected = 0; 
    } else if(megAvailable>memory){ 
     selected = 1; 
    } 

    AlertDialog.Builder builder = new AlertDialog.Builder(this.getParent()); 
    builder.setTitle("Select Storage Path"); 
    builder.setSingleChoiceItems(items, selected, new DialogInterface.OnClickListener() { 
     public void onClick(DialogInterface dialog, int item) { 

      if(item == 0){ 
       rpc.createFoldersInInternalStorage(servername, userId, MyCollectionList.this); 
       Toast.makeText(getApplicationContext(), "Selected Storage Path : Phone Memory", Toast.LENGTH_SHORT).show(); 
       editor.putInt("storagePath", 1); 
       editor.commit(); 
      } else if (item == 1){ 
       rpc.createFoldersInExternalStorage(servername, userId, MyCollectionList.this); 
       Toast.makeText(getApplicationContext(), "Selected Storage Path : SD Card", Toast.LENGTH_SHORT).show(); 
       editor.putInt("storagePath", 2); 
       editor.commit(); 
      } 
     }}); 

     builder.setNegativeButton("Ok", new DialogInterface.OnClickListener() { 
     public void onClick(DialogInterface dialog, int which) { 
       mHandlerUpdateUi.post(mUpdateUpdateUi);  
     } 
     }); 
     AlertDialog alert = builder.create(); 

所以我現在的問題是我設置所選項目根據一些計算,如果我不選擇任何內容,然後按確定,不,我已經被選定的項目事默認它是再次創建對話框,因爲如果用戶沒有選擇任何東西,這就是想法。我試圖設置item=selected;selected=item;,但它不起作用。我知道我的問題是合乎邏輯的,但我無法弄清楚。任何建議如何讓事情發揮作用?

+0

你能具體談談你的問題。 –

+0

這個想法是讓用戶選擇他想要存儲我的應用程序文件的存儲。默認情況下,我設置選擇的存儲空間更多,但問題是如果我不選擇任何項目,並使用默認選定項目單擊確定,它不會設置任何內容。這就是爲什麼我想找到一種方法來使用默認項目,如果用戶不選擇任何東西來創建正確的存儲路徑。 –

回答

1

你可以把那臺你storagePath在連接到NegativeButton的onClickHandler代碼:

final int defaultSelected = selected +1; //this is final since you need to access it in the anonymous inner class; we're adding 1 since your value that you write seems to be either 1 or 2. 
builder.setNegativeButton("Ok", new DialogInterface.OnClickListener() { 
     public void onClick(DialogInterface dialog, int which) { 
       mHandlerUpdateUi.post(mUpdateUpdateUi);  
       editor.putInt("storagePath", defaultSelected); 
       editor.commit(); 
     } 
     }); 
+0

是的,但如果用戶選擇一個項目,我不會得到他的選擇 –

+0

爲什麼不顯示對話框之前,將值設置爲默認值?你可能會做不必要的寫入,但寫入首選對象並不是那麼昂貴。 – Chris

+0

其實我看到我的問題在哪裏,似乎我已經清除了我在應用程序啓動時的所有共享偏好,這就是爲什麼對話每次都會打開,但您的想法仍然正確,因此我會接受您的答案。感謝幫助! –