自定义适配器环境参数 - )getApplicationContext(失败,但“这”作品 [英] context parameter for custom adapter - getApplicationContext() fails but 'this' works
问题描述
我有简单的code段来实现自定义列表视图。
I have simple code snippet to implement custom list view.
在此code,我有 CustomAdapter
延伸类 ArrayAdapter
:
In this code, I have CustomAdapter
class which extends ArrayAdapter
:
CustomAdapter adapter = new CustomerAdapter(getApplicationContext(),R.layout.listview_item_row, weather_data);
的 CustomAdapter
是下面的构造函数:
public CustomerAdapter(Context context, int layoutResourceId, weather[] data) {
super(context, layoutResourceId, data);
mlayoutResourceId = layoutResourceId;
mcontext = context;
mdata = data;
}
如果我写这篇文章,以下错误的logcat显示:
If I write this, the logcat shows following error:
Java.lang.ClassCastException: android.app.Application context can not be cast to android.app.Activity
于是我改变了 getApplicationContext()
到这个
。它工作得很好:
CustomAdapter adapter = new CustomerAdapter(this,R.layout.listview_item_row, weather_data);
所以,我的问题是: 1 为什么我们不能在这里通过应用程序上下文? (用于customadapter)。和
So, my question is : 1. why we can't pass Application context here? (for the customadapter). and
2 哪些是场景中,我们必须要通过活动方面,而不是应用程序上下文的?
2. Which are the scenarios in which we must have to pass Activity context instead of Application context?
[注:我已经看过一些答案<一个href=\"http://stackoverflow.com/questions/16141369/difference-between-getapplicationcontext-and-classname-this\">here和这里,但他们没有在这里具体问题的关注。所有是说,'你可以使用其中的任何',但在这样的具体情况,这是行不通的。所以,请不要标记为重复]
[Note: I have already read some answers here and here, but they do not concern with specific issue here. All are saying that 'you can use any of them', but in specific situation like this, it does not work. So, please do not mark as duplicate.]
推荐答案
适配器不应该获得应用
初始化期间环境。为纽带codeMagic提到的,你应该始终沿着活动
一类对象传递,如果它直接关系到活动的使用寿命< /$c$c>...of的适配器做的。
Adapters should never get the Application
context during initialization. As the link codeMagic mentioned, you should always pass along the Activity
to a class object if it directly relates to the life of the Activity
...of which adapters do.
现在,的确可以给 ArrayAdapter
应用程序上下文。它不会崩溃或抛出一个错误。但是它的作用是使你的意见不同,然后预期。主要是因为应用程序上下文缺少主题化,你可能会或可能不会进行特定活动为您提供的应用程序和/或特异性。
Now, it's certainly possible to give the ArrayAdapter
an application context. It won't crash or throw an error. However what it will do is render your views differently then expected. Mainly because the application context lacks the theming you may or may not have supplied for your App and/or specifically for a given activity.
至于为何发生崩溃?专门出头错了你的code。我猜测,你定义 mcontext
为活动
所以它的自定义构造函数崩溃......或者它定义为一个上下文
但已某处使用的作为导致崩溃的活动内容。
As to why the crash occurs? Somethings specifically wrong with your code. My guess, you are defining mcontext
as an Activity
so its crashing in the custom constructor...or It's defined as a Context
but being used somewhere that as an Activity context which is causing the crash.
这篇关于自定义适配器环境参数 - )getApplicationContext(失败,但“这”作品的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!