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

时间:2018-10-21 14:34:53

标签: java android android-layout string.xml

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

我尝试了String.valueOf和Integer.toString(请参阅下面的ss):

enter image description here

但两者的结果相同(请在下面的ss中引用):

enter image description here

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

您是否知道我可以尝试解决此问题?谢谢您,感谢您抽出宝贵时间回答我的问题。

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

抱歉,我的发展能力真的不好,但是我愿意听和学。

1 个答案:

答案 0 :(得分:1)

向您的函数添加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的camelCase标准(CategoryObjects->`categoryObjects)。

然后,您只需要向其传递一个Context对象即可。

来自活动:

Category.getCategories(this);

来自片段:

Category.getCategories(getActivity());

将来,请粘贴您的代码为 text 。实际上,比截图要容易得多。