2012-03-07 91 views
1

我正在嘗試開發一個由按鈕組成的按鈕,其中單擊按鈕可啓動自定義對話框。該對話框有一個關閉它的按鈕ok。我寫它下面的代碼,但給了我一個NullPointerException自定義對話框中的NullPointerException

Dialog modalDialog; 
@Override 
public void onCreate(Bundle savedInstanceState) { 

    super.onCreate(savedInstanceState); 
    setContentView(R.layout.input); 

    Button modal = (Button)findViewById(R.id.ModalityButton); 

    modal.setOnClickListener(new View.OnClickListener() { 

     @Override 
     public void onClick(View v) { 
      modalDialog = new Dialog(Input.this); 
      modalDialog.setContentView(R.layout.modality); 
      modalDialog.setCancelable(true); 
      Button ok = (Button) findViewById(R.id.modality_ok); 

      ok.setOnClickListener(new OnClickListener() { // shows null pointer error at this line 
       @Override 
       public void onClick(View v) { 
        modalDialog.cancel(); 
       } 
      }); 

      modalDialog.show(); 
     } 
    }); 
} 

回答

6

在對話框的佈局搜索按鈕ok

Button ok = (Button) modalDialog.findViewById(R.id.modality_ok); 
+0

你是什麼意思?在這個佈局中只有一個按鈕,其id爲modality_ok ... – anon 2012-03-07 14:44:50

+0

@anon現在用'findViewById()'查找當前活動佈局中的'Button' ok(用'setContentView() ')。要找到對話框的佈局「R.layout.modality」中的Button OK,您必須在該對話框中搜索其ID。 – Luksprog 2012-03-07 14:47:43

+0

您需要在'findViewById()'之前添加'modalDialog'。您正在搜索活動佈局,而不是在對話框佈局中搜索。 – WarrenFaith 2012-03-07 14:48:31