2011-10-11 27 views
1

我有一個AlertDialog,我只希望在點擊「確定」後啓動下一個活動。問題是在我的方法中,我有本地變量附加到我的意圖,我不能放在onCreateDialog方法。如何在AlertDialog上用戶單擊確定後纔開始活動

//local variable created 
ArrayList<String> students = new ArrayList<String>();  
for(int i=0; i<studentList.size(); i++){ 
    students.add(studentList.get(i).getName()); 
} 

AlertDialog.Builder alertDialog = new AlertDialog.Builder(
        new ContextThemeWrapper(this, R.style.popup_theme)); 
alertDialog.setTitle("Select Game");   
alertDialog.setPositiveButton("3x3", new DialogInterface.OnClickListener() { 
public void onClick(DialogInterface dialog, int which) { 

    //I want the new Activity to start only after user clicks ok. 
    Intent intent=new Intent(getApplicationContext(),NewActivity.class); 
    //Local variable, undefined, cannot reference 
    intent.putStringArrayListExtra("students", students); 
    startActivity(intent); 
    finish(); 
    return; 
    }   
}); 
alertDialog.show(); 

有沒有什麼辦法可以防止showDialog()後的代碼運行,直到用戶點擊OK?我有本地變量,我需要把它放在意圖之內。

+0

你看起來正確的代碼,它會在點擊按鈕時開始活動 –

回答

0

不知道這是一個正確的做法,但我做了一個「黑客」通過使students一個全局變量。會歡迎更好的答案。

4

使用此代碼

AlertDialog.Builder alertDialog = new AlertDialog.Builder(
         new ContextThemeWrapper(this, R.style.popup_theme)); 
    alertDialog.setTitle("Select Game");   
    alertDialog.setMessage("[ Choose Puzzle Matrix ]");  
    alertDialog.setPositiveButton("3x3", new DialogInterface.OnClickListener() { 
    public void onClick(DialogInterface dialog, int which) { 
     Intent myIntent = new Intent(((Dialog) dialog).getContext(), Matrix3x3.class); 
     startActivity(myIntent);  
     return; 
     }   
    });  
    alertDialog.show(); 
+0

是的,我有這個。我無法將用戶名放在我的意圖中,因爲它是一個局部變量。 – newbie

+0

我沒有得到你 –

+0

看看我更新的問題 – newbie

1

品牌students變量final

final ArrayList<String> students = new ArrayList<String>(); 
+0

我想知道爲什麼OP從未嘗試過。 – Shaishav

相關問題