为什么我的应用程序的某些部分适用于一种情况而不适用于另一种情况?

Why parts of my app working with one context and don't work with another?

好的,我有一个 class LibApp,它扩展了应用程序 class 并存储了上下文:

public class LibApp extends Application {
    private static LibApp instance;
    private static Context context;

    private AppModule appModule;
    private AppComponent appComponent;

    @Override
    public void onCreate() {
        super.onCreate();
        ...
        instance = this;
        context = getApplicationContext();
        ...
    }

    public static LibApp getInstance() {
        return instance;
    }

    public static Context getContext() {
        return context;
    }
    ...
}

然后我有 Activity 和 Fragment,这个 Fragment 包含 RecyclerView 和适配器。我的适配器调用了 HomePacksAdapter 并且他注意到 Context 来创建 ImageView。所以,如果我写:

HomePacksAdapter adapter = new HomePacksAdapter(getContext());

一切正常。但是如果我写:

HomePacksAdapter adapter = new HomePacksAdapter(LibApp.getContext()); 

我很喜欢:

android.view.WindowManager$BadTokenException: Unable to add window -- token null is not for an application

我想我不明白 Context 是什么,因为我无法解释为什么一个 Context "better" 是另一个。在我的定义中,Context 是提供应用程序基本功能的对象,那又怎样,应用程序上下文不提供我的适配器需要的那些东西?

getApplicationContext() - Returns 应用程序中所有活动 运行 的上下文。因此,您的家庭适配器只需要 activity 的上下文来扩充视图,而您提供所有活动的上下文,因此它根本无法确定在哪里扩充视图。

getBaseContext() - 如果您想从应用程序中的另一个上下文访问上下文,您可以访问。

getContext() - Returns 只有当前 运行 activity 的上下文视图,这确实是当你使用 getContext() 时它工作正常的原因找到 activity 的上下文来增加视图。

希望对您有所帮助。