EnableListAdapter 中的上下文
我创建了一个 ExpandableListAdapter 类,我需要从访问它的活动向它发送上下文。
MyActivity.class:
MenuExpandableListAdapter.useInstanceContext(getApplicationContext());
MyExpandableListAdapter.class:
static Context context;
public static void useInstanceContext(Context applicationContext) {
context = applicationContext;
}
上面的代码可以工作,但这也可以:
MenuExpandableListAdapter.useInstanceContext(this.getApplicationContext());
有什么区别?这是传递上下文的好方法吗?我仍在尝试完全理解上下文。
I have created an ExpandableListAdapter
class and I need to send it the context from the activity that is accessing it.
MyActivity.class:
MenuExpandableListAdapter.useInstanceContext(getApplicationContext());
MyExpandableListAdapter.class:
static Context context;
public static void useInstanceContext(Context applicationContext) {
context = applicationContext;
}
The above code works, but this also works:
MenuExpandableListAdapter.useInstanceContext(this.getApplicationContext());
What's the difference? Is this a good way to pass context? I'm still trying to fully understand context.
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(3)
为了访问资源和其他一些东西,上下文是必要的。因此,应用程序和活动上下文都有效。但良好的实践是紧抓最有效的最小事情,即您的案例中的活动。因此,我建议您使用新方法:
此外,在您的示例中,调用之间没有区别。
this
只是对当前对象的引用。Context is necessary in order to get access to the resources and some other things. So, both - application and activity contexts work. But a good practice is tight to the smallest thing, which works, which is activity in your case. So, I would suggest new way for you:
Also, in your example, there is no difference between the calls.
this
is just the reference to the current object.this
指的是当前正在执行代码的对象,如果该方法是在同一个类中声明的,并且不是static的,那么调用也是一样的:and
(类成员也是如此)
this
refers to the object that is currently executing code, if the method is declared in the same class, and is not static, it is the same to call:and
(The same applies to class members)
getApplicationContext() 方法将通过使用调用/当前对象隐式调用。
其次,您显式地给出调用/当前对象,因为这是始终引用调用对象的特殊对象。
我建议你使用这个,
因为根据我的阅读,这是一个很好的做法。
The getApplicationContext() method will called by using calling/current object implicitly.
in second you are giving calling/current object explicitly because this is special object that is always refer to calling object.
i suggest you to use this
because as per my reading it's good practice.