android - 如何将大型 int 数组放入 xml 资源文件中?
问题描述
我有大量的整数常量。我想把它们放在数组中。该数组必须可以从不同的活动中访问。如果我将此数组放入 MainActivity.java 中的变量,则从子活动中访问它会出现问题。将它们放入资源(arrays.xml)是一个更大的问题——每个整数值都必须用这个“装饰”:“<item>1234</item>”。有几千个整数值。那么声明这样的数组的最佳方法是什么?
解决方案
您可以在一个类上创建一个私有静态不可修改的最终列表, 并拥有一个公共 getter(并且没有 setter)
我认为重要的是你要两者兼而有之final
,unmodifiable
如果它要保持常量,你不希望任何东西能够改变列表本身或其任何值
public class Constants {
private static final List<Integer> constantsArray =
Collections.unmodifiableList(Arrays.asList(1, 2, 3));
public int getConstantAtIndex(int i) {
return constantsArray.get(i);
}
}
当您返回一个 int 时,无法修改该列表。
甚至将整数作为逗号分隔的字符串放在文件中
public class Constants {
private static final List<Integer> constantsArray = makeList();
private static List<Integer> makeList() {
List<Integer> list = readConstantsFromFile();
return Collections.unmodifiableList(list);
}
private static List<Integer> readConstantsFromFile() {
// Read the file, and get the String ()
String s = <comma spearated string from the file>
String[] a = s.split(",");
List<Integer> list = new ArrayList<>();
for(String v : a) {
list.add(Integer.valueOf(v));
}
return list;
}
public int getConstantAtIndex(int i) {
return constantsArray.get(i);
}
}
推荐阅读
- kotlin - Ktor 中带有 KeyCloak 的 OAuth:它应该像这样工作吗?
- java - Splitting Strings in java without removing the match
- .net - 将文件编译到库中并访问它,但不能作为资源
- xml - Apply-Template 仅适用于 ID 基于父子节点列表的节点
- winapi - 如何捕获菜单栏的激活?
- firebase - google_sign_in 包中的 getServerAuthToken 返回 null
- php - 如何在 Windows 中通过 PHP 运行后台进程?
- okhttp - 如何重现 OkHttp 的错误
- git - 如何使用 Git 将文件添加到现有的 Github 存储库?
- python - Python Pandas - 在特定行上添加列,将特定行从一个数据帧添加到另一个