在DialogFragment中,onCreate应该做什么? [英] In a DialogFragment, what should onCreate do?
问题描述
我目前正在使用DialogFragment来学习使用它.我认为与onCreateView()
相比,onCreate()
可以做到:
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
}
但是我错了.不知道为什么它不起作用.当我注释掉testTextView.setText("Success!");
时,错误消失了
该错误是NullPointerException,然后它仅标记了行39,这是有问题的代码所在的位置.任何澄清都值得赞赏.
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.
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没有指向任何对象,因此请尝试类似
testTextView is NOT pointing to any object so try something like
testTextView = (TextView) findViewById(R.id.testTextView);
如果您看到片段的生命周期,说onCreateView
在之后 onCreate
被称为,因此您的onCreate
没有对对象的任何引用,即布局中的textview
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
这篇关于在DialogFragment中,onCreate应该做什么?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!