2011-06-03 56 views
0

我是Android開發新手。請原諒我如果我的問題很簡單。如何在Android中使用Dialog OnClick Listner?

我試圖在使用XML的Android佈局視圖上創建一個按鈕。現在在Activity類中,我試圖獲取按鈕並在其上添加一個單擊列表器。這工作正常,沒有任何問題。

在按鈕上的類似線條上點擊我之前解釋我彈出一個對話框。在這個對話框中我有一個ImageButton。點擊這個圖像按鈕,我試圖設置一個點擊列表使用下面的代碼。

The Activity on create is as below 

@覆蓋

public void onCreate(Bundle savedInstanceState) { 
    super.onCreate(savedInstanceState); 

    final Button button = (Button) findViewById(R.id.btnAdd);   
    button.setOnClickListener(this); 

} 

@Override 
public void onClick(View v) { 
final Button btnAdd = (Button) findViewById(R.id.btnAdd); 
     if(v==btnAdd) { 
      dialog = new Dialog(this); 
      dialog.setContentView(R.layout.add_dialog); 
      dialog.setTitle("Test Title."); 
      dialog.setCancelable(true); 

      dialog.show(); 

     final ImageButton button = (ImageButton) findViewById(R.id.imageButton1); 
     try { 
      Log.i("Log","1"); 
      button.setOnClickListener(this); 
      Log.i("Log","2"); 

     } 
     catch(Exception e) 
     { 
      Log.i("Log","3"); 
      dialog.dismiss(); 
      //Dialog d = new Dialog(this); 
      //d.setTitle("test."); 
      Toast.makeText(this,e.getMessage(),Toast.LENGTH_LONG).show(); 
      Toast.makeText(this,e.getLocalizedMessage(),Toast.LENGTH_LONG).show(); 
      Toast.makeText(this,e.toString(),Toast.LENGTH_LONG).show(); 
      Log.i("Log","4"); 
      //d.show(); 
      Log.i("Log","5"); 

     } 
    } 

} 

在上面我得到的登錄這個序列。 1,3,4,5。我沒有得到2.在吐司我得到空白的消息,然後是java.lang.Nullexception空白。

但是這個被執行的時候給了我一個關閉的彈出。請建議如何做到這一點。或者是否有相同的解決方法?我需要一個對話框來點擊按鈕,然後在對話框中我需要有多個按鈕選項。對於對話框中的每個按鈕,我需要執行不同的活動。任何形式的幫助或建議都是可觀的。提前感謝您的時間和幫助。

+0

你會得到什麼例外?請顯示logcat輸出 – 2011-06-03 03:21:27

+0

您是否在使用對話框的自定義佈局? – 2011-06-03 03:38:56

+0

是的,我正在使用自定義佈局的對話框。那是錯的嗎? – Vinodtiru 2011-06-03 03:45:40

回答

3

很可能你試圖從Activity類中檢索按鈕。它返回null,因爲此方法只會檢索附加到Activity的資源(使用方法setContentView)。

你有兩個選擇:

  • 您可以使用LayoutInflater
  • 如果要擴展對話框類膨脹的對話框佈局,添加監聽器類中代替。更新後

編輯:

正如我前面所說的,問題是:

final ImageButton button = (ImageButton) findViewById(R.id.imageButton1); 

因爲imageButton1是不是在活動佈局的一部分。只需將其替換爲:

final ImageButton button = (ImageButton) dialog.findViewById(R.id.imageButton1); 
+0

我同意Aleadam。 +1 – 2011-06-03 04:09:53

+0

我也同意。按鈕從活動中檢索。 – 2011-06-03 04:14:21

+0

謝謝你的回覆。我會盡快嘗試,並會讓你知道。謝謝。 – Vinodtiru 2011-06-03 04:27:12

相關問題