简体   繁体   中英

how to implement fragment in android

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.

Try this :

public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState)
{
    if (container == null) {
        return null;
    }
    return (LinearLayout)inflater.inflate(R.layout.your_fragmentlayout_file, container, false);
}



@Override
public void onActivityCreated(Bundle savedInstance)
{
    super.onActivityCreated(savedInstance);
    TextView testTextView = (TextView)getActivity().findViewById(R.id.your_textview_id);
    testTextView.setText("SUCCESS!");
}

where you initalzed testTextView. ? you should do that.........

and also as per fragment life cycle

onAttach(Activity)-->onCreate(Bundle) -->onCreateView(LayoutInflater, ViewGroup, Bundle)->onActivityCreated(Bundle)-->onStart() 

so you should handle this work either in onCreateView or after this...

http://android-developers.blogspot.in/2012/05/using-dialogfragments.html

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.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM