2015-10-18 63 views
0

我想在單擊Activity中的一個片段後,在自定義對話框中設置TextView的值。在被調用之後,Dialog運行正常且具有自定義文本視圖。問題是,它總是顯示NullPointerException當我試圖調用changeMes​​sageText(「你好」)函數。如何在Android中的自定義對話框中設置TextView的值

ProgressDialogFragment.java

public class ProgressDialogFragment extends DialogFragment { 

     private TextView txtMessage; 
     private AlertDialog.Builder mBuilder; 

     public static ProgressDialogFragment newInstance(AlertDialog.Builder builder){ 
      ProgressDialogFragment progressDialogFragment = new ProgressDialogFragment(); 
      progressDialogFragment.mBuilder = builder; 
      return progressDialogFragment; 
     } 

     @Nullable 
     @Override 
     public Dialog onCreateDialog(Bundle savedInstanceState) { 

      View view = getLayoutInflater(savedInstanceState).inflate(R.layout.dialog_progress, null); 
      txtMessage = (TextView) view.findViewById(R.id.txtMessage); 

      changeMessageText("Hello World by default"); // this one works 

      mBuilder.setView(view); 

      return mBuilder.create(); 

     } 
     public void changeMessageText(String text){ 
      txtMessage.setText(text); 
     } 
} 

示例代碼後的按鈕,點擊了

AlertDialog.Builder builder = new AlertDialog.Builder(this); 
ProgressDialogFragment progressDialogFragment = ProgressDialogFragment.newInstance(builder); 
progressDialogFragment.show(getSupportFragmentManager(),"progress_dialog"); 
// dialog box shows until the following function is called. 

progressDialogFragment.changeMessageText("Hello"); 

回答

2

progressDialogFragment.changeMessageText("Hello");叫,尚未創建txtMessage

1)將private String message;加到ProgressDialogFragment

2)改變changeMessageText

public void changeMessageText(String text){ 
    message = text; 
    if(txtMessage != null){ 
     txtMessage.setText(text); 
    }    
} 

3)添加後mBuilder.setView(view);

if(message!=null && !message.isEmpty()){ 
    txtMessage.setText(message); 
} 

4)在onCreateDialog

和刪除changeMessageText("Hello World by default");。它不適合我。

View view = getLayoutInflater(savedInstanceState).inflate(R.layout.dialog_progress, null);

我改變它。

LayoutInflater inflater = getActivity().getLayoutInflater(); 
View view = inflater.inflate(R.layout.dialog_progress, null); 

希望它能幫助你。

+0

謝謝。讓我試試你的代碼,並讓你知道:) – myokyawhtun

相關問題