2011-10-07 31 views
3

我創建了一個選擇AlertDialog的「應用」和「取消」按鈕。當用戶按下「取消」時,我想將選定的項目設置回第一次顯示對話框時的狀態(我已經存儲了該值)。Android:如何在單選AlertDialog中設置選擇?

我知道如何在第一次創建對話框setSingleChoiceItems()時設置所選項目,但是有沒有辦法在以後再次設置?

我想與API級別7兼容,所以我寧願不使用onPrepareDialog()

回答

0

您可以在現場創建對話而不是通過showDialog和onCreateDialog。這樣它總是使用我們給setSingleChoiceItems的當前選擇。

 
//where we display the dialog 

            
 
  
             showDialog(MYDIALOG);
            
  
AlertDialog.Builder builder = new Builder(this); 
String[] choices = {"A","B","C"}; 
builder.setSingleChoiceItems(choices,current_choice,null); 
builder.setPositiveButton("Select",null); 
builder.setNegativeButton("Cancel",null); 
builder.show(); 
... 
protected Dialog onCreatDialog(int id) { 

            
 
  
             if (id==MYDIALOG) { 
     AlertDialog.Builder builder = new Builder(this); 
     String[] choices = {"A","B","C"}; 
     builder.setSingleChoiceItems(choices,current_choice,null); 
     builder.setPositiveButton("Select",null); 
     builder.setNegativeButton("Cancel",null); 
     return builder.show(); 
    }
            
  
    return null; 
}

0

在Altert對話框中爲了創建單一選擇,您使用了單選列表視圖還是單選組? 如果您使用了Single Choice Listviwe,那麼無需擔心。 如果您使用過無線電組,那麼您必須跟蹤在您的活動中使用全局變量的選定單選按鈕。

+0

我用'AlertDialog.Builder.setSingleChoiceItems()',所以我想單一選擇列表視圖。但是,如果我按下取消並稍後返回到對話框,它會顯示取消選擇,它與我的應用程序的當前狀態不匹配。 – Pooks

0

當用戶點擊取消時你想要做什麼。 當用戶點擊取消比你想要從列表中刪除選定的項目,如果是的話,你必須執行以下操作。

在你listitemseleted聽衆

alb.setSingleChoiceItems(items, 0, new OnClickListener() { 

     @Override 
     public void onClick(DialogInterface dialog, int which) { 
      /* which argument is the position of the item in 
       array items you have to remove this item from items array 
       Make your items array global variable.since in java array are 
       immutable you have to use arraylist.Arraylist can be converted 
       to array.*/ 

     } 
    }); 

希望這會幫助,如果任何問題隨時問。

+0

感謝您的回覆,但我不想從列表中刪除該項目。在單個選項列表中,每個元素右側都有一個按鈕。該按鈕對當前選定的元素有效。我想要做的是將當前選定的元素設置回用戶打開對話框時的樣子。 – Pooks

0

好吧,沒有人可以找到解決我的問題,所以我解決了不使用按鈕的對話框。當用戶按下列表中的項目時,該選擇被應用並且對話框被解除。無需記住以前的選擇或支持取消。