2011-10-17 199 views
0

我創建了一個佈局我的對話和OnCreateDialog膨脹佈局的Android空指針異常

/** 
* Object to hold the reference to ListName EditText from Alert_Dialog 
*/ 
private EditText mListNameEditText; 

protected Dialog onCreateDialog(int id) { 
    switch(id) {    
    case DIALOG_TEXT_ENTRY: 

     Log.w(TAG, "In onCreateDialog"); 

     LayoutInflater factory = LayoutInflater.from(this); 
     final View alertDialogView = factory.inflate(R.layout.alert_dialog, null); 
     mListNameEditText = (EditText) findViewById(R.id.listNameText); 
     .../... 
     .../... 
     .../... 

在onPrepareDialog,我試圖讓我鍵入的EditText內的文本,並這會拋出一個空指針異常。請幫忙找出問題

@Override 
protected void onPrepareDialog(int id, Dialog dialog) { 
    switch(id) {    
    case DIALOG_TEXT_ENTRY: 

     Log.w(TAG, "In onPrepareDialog"); 
     mListNameEditText = (EditText) findViewById(R.id.listNameText); 

     if(mListNameEditText == null) 
      Log.w(TAG, "ListName EditText is null"); // This text is printed !! 

     mListNameEditText.setOnKeyListener(new OnKeyListener() { // Exception here because mListNameEditText is NULL 

回答

4

變化

mListNameEditText = (EditText) findViewById(R.id.listNameText); 

mListNameEditText = (EditText) dialog.findViewById(R.id.listNameText); 

你試圖找到在主要佈局(在EditText上你設置使用setContentView(R.layout.whatever);的一個行)。通過將其更改爲我發佈的行,您正在該對話框中搜索EditText

此外,在您的onCreateDialog中,您正在做同樣的事情。您還需要在那裏使用dialog.findViewById(...)