繁体   English   中英

从Android中的ArrayAdapter访问资源

[英]Getting access to resources from an ArrayAdapter in Android

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

<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 ...值,只要我在任何地方使用它。 只是不确定这是否被认为是“最佳实践”。 谢谢

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

喜欢:

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

然后使用:

mContext.getResources()...

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

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM