【问题标题】:How to start activity only after user clicks ok on AlertDialog如何仅在用户单击 AlertDialog 上的确定后才开始活动
【发布时间】:2011-10-19 03:03:08
【问题描述】:

我有一个 AlertDialog,我只希望在单击“确定”后启动下一个 Activity。问题出在我的方法中,我的意图附加了局部变量,我无法放入 onCreateDialog 方法。

//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() 之后的代码运行,直到用户单击“确定”?我有需要放入意图中的局部变量。

【问题讨论】:

  • 你的代码看起来是正确的,当点击按钮时它会启动活动

标签: android android-activity android-alertdialog


【解决方案1】:

使用此代码

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

【讨论】:

  • 是的,我有这个。我无法将用户名放在我的意图中,因为它是一个局部变量。
  • 你想将数据从一个活动转移到另一个活动。
  • 是的,没错。我通过让学生成为全局变量来进行“破解”......有更好的主意吗?
【解决方案2】:

使students 变量final

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

【讨论】:

    【解决方案3】:

    不确定这是否是正确的方法,但我通过将students 设为全局变量进行了“破解”。欢迎提供更好的答案。

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2021-12-07
      • 1970-01-01
      • 1970-01-01
      • 2011-05-10
      • 1970-01-01
      相关资源
      最近更新 更多