在ArrayAdapter中使用传递的上下文 [英] Using the passed Context in an ArrayAdapter

查看:143
本文介绍了在ArrayAdapter中使用传递的上下文的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

在我的ArrayAdapter类中,我捕获了传入的上下文.然后将其放入getView方法中,获得了if语句:

In my ArrayAdapter class I capture the context passed in. Then int the getView method, I have this if statement:

if(m.getSide() == RED) {
    v.setBackgroundColor(lc.getResources().getColor(R.color.red_bouy));
    Log.d("MA", "HERE");
} else if(m.getSide() == BLACK) {
    v.setBackgroundColor(lc.getResources().getColor(R.color.black_bouy));
}

(lc是我从构造函数中获取的上下文)

(lc is the Context I grab from the Constructor)

如果我仅使用Color.red,则可以找到它.我见过的所有示例都使用ghet getResources ...,但是来自活动中.
有什么建议吗?

If I just use Color.red, it works find. All examples I've seen use ghet getResources..., but from within an activity.
Any suggestions?

推荐答案

创建适配器时,您将 Context 传递给构造函数.在 getView()中,您可以调用 getContext().getResources().get ...这是您要找的吗?

When you create adapter, you pass a Context to constructor. In getView() you can call getContext().getResources().get... Is this what you were looking for?

此外,@ MahdeTo是正确的:您似乎保留了对上下文的实时引用-不用!您会泄漏上下文.如果绝对必要,请使用 WeakReference < Context>并检查 null ,但我不明白为什么要这么做.

Also, @MahdeTo is right: you seem to keep a live reference to context - don't! You'll leak your context. If you absolutely must, use WeakReference<Context> and check for null, but I don't see why you would have to.

UPD :Adapter并不是一个真正的问题(tnx指向@Arhimed和@Rperryng指出了这一点),因为它们的正确用法可确保其生命周期不超过其,因此可以将实时链接存储到Context [,即使适配器本身在Context中具有实时引用-GC也很聪明,不会被循环引用所欺骗] em>.不过,在这种情况下无需这样做:ArrayAdapter.getContext()正是出于这一确切目的-因此,当您需要在getView()

UPD: Not really a problem with Adapters (tnx to @Arhimed and @Rperryng for pointing this out) since their proper usage ensures their lifecycle doesn't exceed that of their Context, so it's ok to store a live link to a Context [even if the adapter itself has a live ref in the Context -- GC is pretty smart, isn't fooled by circular refs]. Nevertheless, there's no need to do that in this case: ArrayAdapter.getContext() is there for this exact purpose - so you can access resources and get an Inflater when you need one to build views in getView()

这篇关于在ArrayAdapter中使用传递的上下文的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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