我创建了一个ExpandableListAdapter类,我需要从访问它的活动中向其发送上下文。

MyActivity.class:

MenuExpandableListAdapter.useInstanceContext(getApplicationContext());


MyExpandableListAdapter.class:

static Context context;
public static void useInstanceContext(Context applicationContext) {
    context = applicationContext;
}


上面的代码有效,但这也有效:

MenuExpandableListAdapter.useInstanceContext(this.getApplicationContext());


有什么不同?这是传递上下文的好方法吗?我仍在尝试完全理解上下文。

最佳答案

为了访问资源和其他一些东西,上下文是必需的。因此,应用程序和活动上下文均有效。但是,良好的实践会紧紧牵扯到最小的事情,而这是可行的,这就是您的情况。因此,我将为您提出新的建议:

MenuExpandableListAdapter.useInstanceContext(this);


同样,在您的示例中,调用之间没有区别。 this只是对当前对象的引用。

10-07 20:00
查看更多