问题
Background:
- I just want to create a customDialog with a specific layout and add the content.
- Its a DialogFragment
Code:
TextView text;
@Override
public void onCreate(Bundle savedInstanceState){
super.onCreate(savedInstanceState);
text = (TextView)getView().findViewById(R.id.lorem);
text.setText("Test");
}
@Override
public Dialog onCreateDialog(Bundle savedInstanceState){
AlertDialog.Builder builder = new AlertDialog.Builder(getActivity());
LayoutInflater inflater = getActivity().getLayoutInflater();
builder.setView(inflater.inflate(R.layout.custom_dialog, null));
return builder.create();
}
Problem:
- The Dialog worked, but after I started to add the the lines in "onCreate" I got a NullPointerException Error. I hope someone can help me.
Thanks @Raghunandan for the Answer + explanation and here is the working code:
@Override
public Dialog onCreateDialog(Bundle savedInstanceState){
AlertDialog.Builder builder = new AlertDialog.Builder(getActivity());
LayoutInflater inflater = getActivity().getLayoutInflater();
View view = inflater.inflate(R.layout.custom_dialog_style, null);
textView = (TextView)view.findViewById(R.id.your_textview);
textView.setText("Test");
builder.setView(view);
return builder.create();
}
回答1:
At first i thought its a Activity
now i see its a DialogFragment
.
I am guessing the view belongs to custom_dialog.xml
View view = inflater.inflate(R.layout.custom_dialog, null);
text = (TextView)view.findViewById(R.id.lorem);
builder.setView(view);
So use the view object to initialize TextView
.
text = (TextView)getView().findViewById(R.id.lorem);
here getView()
returns null.
You are calling setText
on null leading to NullPointerException
.
来源:https://stackoverflow.com/questions/25363263/nullpointerexception-while-changing-textview-text-in-an-alertdialog