自定义适配器的上下文参数-getApplicationContext()失败,但' this'作品 [英] context parameter for custom adapter - getApplicationContext() fails but 'this' works

查看:109
本文介绍了自定义适配器的上下文参数-getApplicationContext()失败,但' this'作品的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有简单的代码片段来实现自定义列表视图.

I have simple code snippet to implement custom list view.

在此代码中,我有 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()更改为 this .效果很好:

So I changed getApplicationContext() to this. and it worked fine:

 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?

[注意:我已经在此处此处,但他们并不关心此处的特定问题.所有人都在说您可以使用它们中的任何一个",但是在这样的特定情况下,它是行不通的.因此,请不要将其标记为重复项.]

[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.]

推荐答案

在创建适配器对象时,应传递活动的上下文.应用程序上下文不同于活动上下文,因此永远不应互换.使用应用程序上下文为您提供了应用程序的整个上下文,这取决于您如何设置应用程序子类.虽然它仍然可以编译,但可能会产生您所不期望的结果.崩溃的原因是由于Application子类中已包含哪些内容,并且可能特定于您的案例.

You should pass the context of your activity while creating an adapter object. Application context is different from the activity context and they should never be interchanged. Using application context gives you the entire context for the application which depends on how you have set up your Application subclass is set up. While it can still compile, it may produce results that you do not expect. The reason for your crash is because of what has gone into your Application subclass and is likely specific to your case.

简单地说,适配器对象应该使用本地Activity上下文,因为它是绑定到的本地上下文.

Simply put, adapter objects should use the local Activity context as this is the one that it is bound to.

这篇关于自定义适配器的上下文参数-getApplicationContext()失败,但' this'作品的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
相关文章
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆