taken from http://developer.android.com/guide/topics/ui/settings.html:
Note: A PreferenceFragment doesn't have a its own Context object. If you need a Context object, you can call getActivity(). However, be careful to call getActivity() only when the fragment is attached to an activity. When the fragment is not yet attached, or was detached during the end of its lifecycle, getActivity() will return null.
If I call getActivity() from within the OnCreate() method of a PreferenceFragment then can I be assured that the fragment is attached to its activity - or is there some other way you should get the Context in this instance?
The reason I need a Context is I'm trying to use a Toast notification from the PreferenceFragment
If you want to make sure that a Context is available you'll need to wait until the Fragment has been attached to an Activity. The callback for this is the onAttach(Activity)
method.
Depending on the lifecycle state of your fragment the getActivity()
method can also return null.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With