Arraylist 在一个单独的 java 文件中既不是 activity 也不是片段,如何从 string.xml 中获取字符串值?

Arraylist in a separate java file neither an activity or fragment, how to get the string value from string.xml?

美好的一天,我想知道或寻求帮助。我很难从我的应用程序 string.xml 中获取字符串值。我正在通过 Arraylist 访问它(在单独的 java 文件中。arraylist 不在 activity 或片段内)。

我试了String.valueOf和Integer.toString(参考下面ss):

但是两者的结果是一样的(请参考下面ss):

左边的项目应该是我 string.xml 中的字符串值,但我不知道如何以及为什么。我也试过 Resources.getString 但它使应用程序崩溃。

你知道我可以尝试解决这个问题吗?谢谢,非常感谢您抽出时间回答我的问题。

编辑:这是代码(请参阅下面的 ss),我也尝试了 getString() 建议。

不好意思我开发真的不行,但我愿意倾听和学习。

向您的函数添加一个 context 参数:

public static ArrayList<CategoryObject> getCategories(Context context) {
    final ArrayList<CategoryObject> categoryObjects = new ArrayList<>();
    final Resources resources = context.getResources();

    CategoryObject categoryObject = new CategoryObject();
    categoryObject.setCategoryTitle(resources.getString(R.string.psi));
    categoryObject.setItem1(resources.getString(R.string.psi1));
    categoryObject.setItem2(resources.getString(R.string.psi2));
    categoryObject.setItem3(resources.getString(R.string.psi3));
    categoryObject.setItem4(resources.getString(R.string.psi4));

    categoryObjects.add(categoryObject);

    return categoryObjects;
}

请注意,我更改了您的 ArrayList 变量名称以使用 Java 的驼峰命名法标准 (CategoryObjects --> `categoryObjects).

然后你只需要传递一个上下文对象给它。

来自 Activity:

Category.getCategories(this);

来自片段:

Category.getCategories(getActivity());

以后,请将您的代码粘贴文本。其实比截图简单多了。