2011-11-18 61 views
5

我在應用程序的開始部分創建一個提醒對話框,讓用戶選擇存儲我的應用程序從Web下載的數據的位置。我現在想要實現的是取決於內部/外部存儲的大小,我想設置所選項目中的一個。下面是我使用創建對話框代碼:Android在提醒對話框中設置選定項目

@SuppressWarnings("static-access") 
public void createDialog(){ 


    final CharSequence[] items = {"Phone Memory - "+memorysize+" free space", "SD Card - "+megAvailable+" MB free space"}; 

    final int userId = rpc.getUserId(this); 
    final String servername = rpc.getCurrentServerName(this); 

    SharedPreferences stampiiSettings = PreferenceManager.getDefaultSharedPreferences(MyCollectionList.this); 
    final SharedPreferences.Editor editor = stampiiSettings.edit(); 

    AlertDialog.Builder builder = new AlertDialog.Builder(this.getParent()); 
    builder.setTitle("Select Storage Path"); 
    builder.setSingleChoiceItems(items, -1, 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.setPositiveButton("Ok", new DialogInterface.OnClickListener() { 
     public void onClick(DialogInterface dialog, int which) { 
       mHandlerUpdateUi.post(mUpdateUpdateUi); // update UI    
     } 
     }); 
     AlertDialog alert = builder.show(); 
} 

而且我想要實現的另一件事,我怎樣才能防止用戶關閉警告對話框,如果他沒有選擇任何項目。我不想關閉按下後退按鈕或單擊確定按鈕時的對話框。歡迎任何想法/建議/幫助!

回答

17

做這樣的事情:

int selected = 0; // or whatever you want 
builder.setSingleChoiceItems(items, selected, new DialogInterface.OnClickListener() { 
    public void onClick(DialogInterface dialog, int item) { 
       //onclick 
    }}); 
3

關閉按鈕,您可以定義確定取消按鈕像這樣

builder.setNegativeButton("Cancel", new DialogInterface.OnClickListener() { 
     public void onClick(DialogInterface dialog, int which) { 
      // no need to write anything here just implement this interface into this button 
     } 
}); 

對選定的項目,你可以做微調地方定義這個類,或者您可以將此值分配給任何變量喜歡選擇。

int selected = 0; // if you want in integer or 
String selected = "internal"; // you can go with string 

現在你可以通過默認值設置到這一點,並獲得當你點擊對話框中的OK按鈕,在值

builder.setPositiveButton("Ok", new DialogInterface.OnClickListener() { 
    public void onClick(DialogInterface dialog, int which) { 
      // here get the selected item value 
    } 
}); 
相關問題