【问题标题】:Getting access to resources from an ArrayAdapter in Android从 Android 中的 ArrayAdapter 获取资源的访问权限
【发布时间】:2012-01-03 07:09:21
【问题描述】:

我定义了一些资源,例如:

<color name="lightGrey">#FFCCCCCC</color>
<integer name="KEY_POSITION_ARM">2</integer>

...我有一个 ArrayAdapter 向 TextViews 显示项目。我正在尝试使用以下代码访问值:

keyPosition = getResources().getInteger(R.integer.KEY_POSITION_ARM);
moduleDataView.setTextColor(getResources().getColor(R.color.darkgreen));

...但我收到类似“方法 getResources() 未定义类型 ContinuityAdapter”的错误。 (ContinuityAdapter 扩展了 ArrayAdapter)

有什么好的办法吗?

谢谢

这是一个例子:

switch (currentModule.keyPosition) {
case activity.getResources().getInteger(R.integer.KEY_POSITION_ARM):
    moduleDataView.keyPosition.setText("TEST");
    moduleDataView.keyPosition.setTextColor(Color.GREEN);
    break;
case R.integer.KEY_POSITION_ARM:
    moduleDataView.keyPosition.setText("ARM");
    moduleDataView.keyPosition.setTextColor(Color.RED);
    break;
}

第一种情况给出错误,第二种情况没有但也不使用 XML 文件中的值。尽管正如您所说,只要我在任何地方都以这种方式使用它,我就可以使用 R... 值。只是不确定这是否被认为是“最佳实践”。谢谢

【问题讨论】:

    标签: java android android-arrayadapter


    【解决方案1】:

    你需要一个Context 对象来调用Context.getResources() 方法。通常,您可以通过自定义适配器的构造函数传递 Context 或其子类(即 Activity)。

    喜欢:

    public ContinuityAdapter extends ArrayAdapter {
        private final Context mContext;
        ...
        public ContinuityAdapter(Context context) {
            mContext = context;
        }
    }
    

    然后使用:

    mContext.getResources()...
    

    编辑: 这似乎是避免切换的情况。见:

    【讨论】:

    • 谢谢。我试过了,我认为它不起作用,但现在我意识到我遇到了另一个错误:'switch (foo) { case activity.getResources().getInteger(R.integer.KEY_POSITION_ARM):' The case语句显然需要一个常量表达式,即使资源是常量。我是否坚持使用 if 语句?
    • 我需要查看更多代码。通常我会尽量避免切换 case 或直接使用资源 id(即 case R.id.xyz)。
    • 我编辑了问题以包含更好的代码示例。谢谢
    猜你喜欢
    • 2019-08-06
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2023-03-24
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多