I am currently messing around with DialogFragment to learn to use it. I assumed that compared to onCreateView()
, onCreate()
can do this:
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
testTextView.setText("SUCCESS!"); //ERROR HERE
}
But I am wrong. Not sure why its not working. The error goes away when I comment out testTextView.setText("Success!");
The error is a NullPointerException, and then it just flags line 39 which is where the offending line of code is. Any clarifications much appreciated.
EDIT:
public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState){
View testView = (View)inflater.inflate(R.layout.test_dialog_file, container, false);
//instantiated testTextView globally
testTextView = (TextView)testView.findViewById(R.id.set_text);
testTextView.setText("SUCCESS!");
return testView;
}
testTextView is NOT pointing to any object so try something like
testTextView = (TextView) findViewById(R.id.testTextView);
EDIT:
If you see the lifecycle of a fragment, it says that onCreateView
is called after onCreate
hence your onCreate
doesn't have any reference to your object, that is textview in your layout
You haven't used setContentView
yet, so you are getting a NPE for the TextView.
onCreate
happens before onCreateView
. If you want to access something from the layout there, you need to setContentView
... which is not a good idea for a DialogFragment.
Move that bit of code to onCreateView
after you setContentView
and you'll be ok.
For your reference, here's the Fragment Lifecycle:
Did you initialize the testTextView in onCreateView? You have to use a LayoutInflater in onCreateView to get the Layout and then you have to access the TextView via findViewById.
来源:https://stackoverflow.com/questions/11046075/in-a-dialogfragment-what-should-oncreate-do