2013-06-12 23 views
0

我搜索了互联网,但没有找到好的东西。将几个AliertDialogs处理成一个Dialog.onClickListener

所以我试图找到我的方式来解决这个问题。 我找到了一个,但是现在我想问一下,这个太脏了解决方案,是否用过,是否危险?

import android.app.Activity; 
import android.app.AlertDialog; 
import android.content.DialogInterface; 
import android.content.DialogInterface.OnClickListener; 
import android.os.Bundle; 

public class MyActivity extends Activity implements OnClickListener { 

    public void onCreate(Bundle b) { 
     new AlertDialog.Builder(this) 
     .setTitle("Title1") 
     .setPositiveBUtton("Ok",this) 
     .show(); 
     new AlertDialog.Builder(this) 
     .setTitle("Title2") 
     .setPositiveButton("Ok",this) 
     .show(); 
    } 

    @Override 
    public void onClick(DialogInterface dialog, int id) { 
     String dialogTitle = ((AlertDialog)dialog).getActionBar().getTitle().toString(); 
     if(dialogTitle.equals("Title1")) { 
     switch(id) { 
      //do smth 
     } 
     } else if(dialogTitle.equals("Title2")) { 
     switch(id) { 
      //do smth 
     } 
     } else { 
     //no such dialog 
     } 
    } 
} 

回答

0

这似乎令人难以置信的脆弱。我会建议只使用多个监听器,每一个对话框:

private DialogInterface.OnClickListener mFirstListener = new DialogInterface.OnClickListener() { 
    @Override 
    public void onClick (DialogInterface dialog, int which) { 
     //Handle first dialog 
    } 
}; 

private DialogInterface.OnClickListener mSecondListener = new DialogInterface.OnClickListener() { 
    @Override 
    public void onClick (DialogInterface dialog, int which) { 
     //Handle second dialog 
    } 
}; 

然后,只需按指定对话框中听众:

new AlertDialog.Builder(this) 
    .setTitle("First Dialog") 
    .setPositiveButton("Ok", mFirstListener) 
    .show(); 
+0

是的,我知道其他方式,从而例如很少听众(匿名或不),并使用它们。只是想找到另一种解决方案。 – AlpenDitrix

+0

这些几乎是你的选择。没有任何标识信息会在事件中传递(没有做一些不能保证的安全投射),因此您可以在应用程序中保持一些当前状态(增加不必要的复杂性),或者只使用另一个监听器。 – kcoppock