0

我在互联网上搜索过,但没有找到好的东西。

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

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
      }
   }
}
4

1 回答 1

0

That seems incredibly fragile. I would recommend just using multiple listeners, one for each dialog:

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
    }
};

Then just assign a listener per dialog:

new AlertDialog.Builder(this)
    .setTitle("First Dialog")
    .setPositiveButton("Ok", mFirstListener)
    .show();
于 2013-06-12T23:41:30.297 回答