android – 在PreferenceFragment中的上下文

取自 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.

如果我从PreferenceFragment的OnCreate()方法调用getActivity(),那么我可以放心,片段是附加到它的活动的 – 还有其他方法你应该得到这个实例中的Context?

我需要上下文的原因是我正在尝试使用PreferenceFragment中的Toast通知

解决方法

如果要确保可用的上下文,则需要等到片段已附加到活动.这个回调是 onAttach(Activity)方法.

根据片段的生命周期状态,getActivity()方法也可以返回null.

相关文章

Android性能优化——之控件的优化 前面讲了图像的优化,接下...
前言 上一篇已经讲了如何实现textView中粗字体效果,里面主要...
最近项目重构,涉及到了数据库和文件下载,发现GreenDao这个...
WebView加载页面的两种方式 一、加载网络页面 加载网络页面,...
给APP全局设置字体主要分为两个方面来介绍 一、给原生界面设...
前言 最近UI大牛出了一版新的效果图,按照IOS的效果做的,页...