2012-10-18 53 views
0

我使用layoutInflater從佈局創建我的自定義AlertDialog。在這個佈局中,我找到了我的按鈕,並在這個按鈕上設置了OnClickListener。問題是,在方法onClick不存在DialogInterface,我無法做dialog.dissmiss。我怎樣才能得到我的AlertDialog上的指針,或者在DialogInterface上?如何從onClick方法獲取自定義AlertDialog上的指針?

AlertDialog.Builder builder; 
    LayoutInflater inflater = (LayoutInflater) myApp.getSystemService(Context.LAYOUT_INFLATER_SERVICE); 
    View layout = inflater.inflate(R.layout.my_dialog, null); 
    ((Button) layout.findViewById(R.id.downloadButton)).setOnClickListener(new OnClickListener() 
    { 
     @Override 
     public void onClick(View v) 
     { 
      //in this, i want to dissmiss dialog 
      //some code 
     } 
    }); 

我不希望保存類屬性上的對話框上的指針 - 也許其他方式都存在? 謝謝:)

回答

0

你可以通過使用Dialog類以下面的方式來做。

final Dialog dialog = new Dialog(MAinActivity.this); 
dialog.setContentView(R.layout.login_popup); 
Button dialogButtonOk = (Button) dialog.findViewById(R.id.dialogButtonOK); 

dialogButtonOk.setOnClickListener(new OnClickListener() 
     { 
      @Override 
      public void onClick(View v) 
      { 
         dialog.dismiss(); 
} 
} 
+0

非常感謝!那就是我需要的!我不能使用AlertDialog,因爲它會在創建Buailder之後創建。 Dialog解決了這個問題。謝謝,非常有幫助! – kolombo

0

我只是在做這個...我希望我沒有刪除任何東西出來的,重要的是不是無關,你在做什麼。

public class updateDialog extends AlertDialog implements AlertDialog.OnClickListener { 
    updateDialog(Context context, Object sent) 
    { 
     super(context,R.style.MyAlertDialogStyle); 
     // Inflate your view 
     View myView = getLayoutInflater().inflate(R.layout.update_sql,null); 
     // Set it to be the view 
     setView(myView); 
     // Set up buttons 
     setButton(BUTTON_NEGATIVE, context.getString(Cancel), this); 
     setButton(BUTTON_NEUTRAL,context.getString(R.string.Propose), this); 
     setButton(BUTTON_POSITIVE, context.getString(R.string.Restore), this); 
    } 

    // Handle buttons 
    @Override 
    public void onClick(DialogInterface dialogInterface, int i) { 
     switch (i) 
     { 
      case BUTTON_NEGATIVE: 
       // Dismiss the dialog. 
       dialogInterface.dismiss(); 
       break; 
      case BUTTON_NEUTRAL: 
       break; 
      case BUTTON_POSITIVE: 
       break; 
     } 
    } 

大多數情況下,關鍵不是使用構建器,而是自己構建它。

相關問題