【发布时间】:2015-10-18 01:14:00
【问题描述】:
单击 Activity 中的片段之一后,我想在自定义对话框中设置 TextView 的值。对话框在被调用后使用自定义文本视图运行良好。问题是当我尝试调用 changeMessageText("Hello") 函数时,它总是显示 NullPointerException。
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");
【问题讨论】: