In a DialogFragment, what should onCreate do?

大兔子大兔子 提交于 2019-12-06 14:38:12

问题


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;
}

回答1:


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




回答2:


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:




回答3:


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

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!