Sye*_*Ali 8 java android android-fragments
我想到的是使用两个片段,第一个用于显示联系人列表,第二个用于显示在上层片段中选择的联系人的详细信息.由于上下文问题
,我用来扩展Fragment类的类不允许我使用getContentResolver()
方法.现在我正在尝试在同一个类中获取联系人,该类正在扩展Fragment类并使用它来显示列表视图及其详细信息.在经历了一些较旧的解决方案之后,我找到了创建函数的方法并将Context作为参数传递给它,但问题是我不必从任何其他扩展Activity的类中调用它.我想从扩展Fragment的同一个类中做到这一点.
我该怎么做?
任何帮助将受到高度赞赏.
Ahm*_*idi 11
尝试将此代码添加到以前的活动:
// a static variable to get a reference of our application context
public static Context contextOfApplication;
public static Context getContextOfApplication()
{
return contextOfApplication;
}
Run Code Online (Sandbox Code Playgroud)
并在同一活动中,在onCreate方法中添加以下行:
contextOfApplication = getApplicationContext();
Run Code Online (Sandbox Code Playgroud)
在您的片段中,您可以使用以下方式访问它:
Context applicationContext = YourActivity.getContextOfApplication();
applicationContext.getContentResolver();
Run Code Online (Sandbox Code Playgroud)
小智 9
使用getter获取应用程序上下文不起作用.相当于上面的答案是
getActivity().getApplicationContext().getContentResolver().
Run Code Online (Sandbox Code Playgroud)