开发者

How to start activity only after user clicks ok on AlertDialog

开发者 https://www.devze.com 2023-04-12 09:51 出处:网络
开发者_如何学GoI have an AlertDialog and I only want the next Activity to start after I have click \"OK\". The problem is in my method, I have local variables attached to my intent and I cannot put in

开发者_如何学GoI have an AlertDialog and I only want the next Activity to start after I have click "OK". The problem is in my method, I have local variables attached to my intent and I cannot put in the onCreateDialog method.

//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();

Is there any way I can prevent the code after showDialog() from running until the user clicks OK? I have local variable that I need to put inside the intent.


use this code

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();


Make students variable final.

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


Not sure if this is a right way but I did a 'hack' by making students a global variable. Would welcome better answers.

0

精彩评论

暂无评论...
验证码 换一张
取 消

关注公众号