I want to set the value of TextView in custom dialog box after I clicked in one of the fragments in Activity. Dialog was running fine with custom text view after it is being called. The problem is that it always shows NullPointerException when I tried to call changeMessageText("Hello") function.
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);
}
}
Sample Code after the button Clicked
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");
When progressDialogFragment.changeMessageText("Hello");
called, txtMessage
is not created yet.
1) Add private String message;
to ProgressDialogFragment
.
2) Change changeMessageText
public void changeMessageText(String text){
message = text;
if(txtMessage != null){
txtMessage.setText(text);
}
}
3) add after mBuilder.setView(view);
if(message!=null && !message.isEmpty()){
txtMessage.setText(message);
}
4) Remove changeMessageText("Hello World by default");
in onCreateDialog
And. It Doesn't Work for Me.
View view = getLayoutInflater(savedInstanceState).inflate(R.layout.dialog_progress, null);
I change it.
LayoutInflater inflater = getActivity().getLayoutInflater();
View view = inflater.inflate(R.layout.dialog_progress, null);
Hope it will help you.
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.