从Android中的ArrayAdapter访问资源

ARQ*_*ttr 8 java android android-arrayadapter

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

<color name="lightGrey">#FFCCCCCC</color>
<integer name="KEY_POSITION_ARM">2</integer>
Run Code Online (Sandbox Code Playgroud)

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

keyPosition = getResources().getInteger(R.integer.KEY_POSITION_ARM);
moduleDataView.setTextColor(getResources().getColor(R.color.darkgreen));
Run Code Online (Sandbox Code Playgroud)

...但是我得到的错误是"方法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;
}
Run Code Online (Sandbox Code Playgroud)

第一种情况给出错误,第二种情况不会,但也不使用XML文件中的值.虽然正如你所说,我可以只使用R ...值,只要我在任何地方使用它.只是不确定这是否被认为是"最佳实践".谢谢

use*_*421 23

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

喜欢:

public ContinuityAdapter extends ArrayAdapter {
    private final Context mContext;
    ...
    public ContinuityAdapter(Context context) {
        mContext = context;
    }
}
Run Code Online (Sandbox Code Playgroud)

然后使用:

mContext.getResources()...
Run Code Online (Sandbox Code Playgroud)

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