2011-10-03 9 views
6
AlertDialog 2つの AlertDialogオブジェクトがあります。

DialogInterface.OnClickListenerを使用して単一のダイアログを区別する

AlertDialog dialog1, dialog2; 

両方のダイアログはAlertDialog.Builderで作成されます。
どのダイアログがDialogInterface.OnClickListenerのイベントのソースであるかをどのように認識できますか?

単一のダイアログでこれを行うことができます:

AlertDialogInstance.setOnClickListener(myListener); 

//myListener 
public void onClick(DialogInterface arg0, int arg1) { 
     switch (arg1) { 
      case AlertDialog.BUTTON_NEGATIVE: 
       // do something 
       break; 
      case AlertDialog.BUTTON_POSITIVE: 
       // do something 
       break; 
      case AlertDialog.BUTTON_NEUTRAL: 
       // do something 
       break; 
     } 
    } 

このswitchロジックを変更して複数のダイアログを処理する方法は?
(または、インラインボタンコールバック以外の、ダイアログを処理するシステムがあれば、それは何ですか?)

答えて

5

カスタムリスナーに必要なparamを入れることをお勧めします。

private class CustomOnClickListener implements OnClickListener { 
    private int id; 

    public CustomOnClickListener(int id) { 
     this.id = id; 
    } 

    public void onClick(DialogInterface dialog, int which) { 
      //check id and which 
     } 

} 

次に、ダイアログにonClickListenersを追加すると、リスナーにIDを渡すだけです。あなたのダイアログが微分コンテンツを持っている場合は

3
private AlertDialog dialog1; 
private AlertDialog dialog1; 

@Override 
protected void onCreate(final Bundle savedInstanceState) 
{ 
     super.onCreate(savedInstanceState); 
     dialog1 = new AlertDialog.Builder(this).setTitle("dialog1").create(); 
     dialog1.setButton(AlertDialog.BUTTON_POSITIVE, "Yes", this); 

     dialog2 = new AlertDialog.Builder(this).setTitle("dialog2").create(); 
     dialog2.setButton(AlertDialog.BUTTON_NEGATIVE, "NO", this); 
    } 
@Override 
public void onClick(final DialogInterface dialog, final int which) 
{ 
    if (dialog == dialog1) 
    { 
     if (which == AlertDialog.BUTTON_POSITIVE) 
     { 
      // 
     } 
     else if (which == AlertDialog.BUTTON_NEGATIVE) 
     { 
      // 
     } 
    } 
    else if (dialog == dialog2) 
    { 
     if (which == AlertDialog.BUTTON_POSITIVE) 
     { 
      // 
     } 
     else if (which == AlertDialog.BUTTON_NEGATIVE) 
     { 
      // 
     } 
    } 
} 
+0

オブジェクトの比較は、整数の比較よりも悪いです。 – QuickNick

+0

これは最悪の考えです。また、DialogFragmentsを使用すると、そこにAlertDialogを作成し、あなたのアクティビティ(onClick()がある場所)にフィールドとして保持する必要はありません。 – pjv

0

、あなたは明らかにその内容が直接対話を伝えることができます:もちろん

if(which==AlertDialog.BUTTON_NEGATIVE)return; 
AlertDialog theDialog = (AlertDialog)dialog; 
if(theDialog.findViewById(R.id.phoneinput)!=null) ...;//handle the phone 
if(theDialog.findViewById(R.id.emailinput)!=null) ...;//handle the email 

は解決策は普遍的な、しかし、いくつかのケースで非常に便利ではありません。

関連する問題