Java 从Android程序中的xml资源获取整数数组

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/2064595/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-13 03:09:12  来源:igfitidea点击:

Get an integer array from an xml resource in Android program

javaandroid

提问by JERiv

Just a quickie,

只是一个快手,

i have an xml resource in res/values/integers.xml

我在 res/values/integers.xml 中有一个 xml 资源

<?xml version="1.0" encoding="utf-8"?>
<resources>
     <integer-array name="UserBases">
          <item>2</item>
          <item>8</item>
          <item>10</item>
          <item>16</item>
     </integer-array>
</resources>

and ive tried several things to access it:

我尝试了几件事来访问它:

int[] bases = R.array.UserBases;

this just returns and int reference to UserBases not the array itself

这只是返回对 UserBases 的 int 引用,而不是数组本身

int[] bases = Resources.getSystem().getIntArray(R.array.UserBases);

and this throws an exception back at me telling me the int reference R.array.UserBases points to nothing

这会向我抛出一个异常,告诉我 int 引用 R.array.UserBases 指向任何内容

what is the best way to access this array, push it into a nice base-type int[] and then possibly push any modifications back into the xml resource.

访问此数组的最佳方法是什么,将其推送到一个不错的基本类型 int[] 中,然后可能将任何修改推送回 xml 资源。

I've checked the android documentation but I haven't found anything terribly fruitful.

我检查了 android 文档,但我没有发现任何非常有成效的东西。

采纳答案by Dan Lew

You need to use Resources to get the int array; however you're using the system resources, which only includes the standard Android resources (e.g., those accessible via android.R.array.*). To get your own resources, you need to access the Resources via one of your Contexts.

需要使用Resources来获取int数组;但是,您使用的系统资源仅包括标准的 Android 资源(例如,可通过 访问的资源android.R.array.*)。要获得您自己的资源,您需要通过您的上下文之一访问资源。

For example, all Activities are Contexts, so in an Activity you can do this:

例如,所有活动都是上下文,因此在活动中您可以这样做:

Resources r = getResources();
int[] bases = r.getIntArray(R.array.UserBases);

This is why it's often useful to pass around Context; you'll need it to get a hold of your application's Resources.

这就是为什么传递 Context 通常很有用的原因;您将需要它来获取应用程序的资源。