首页 > 解决方案 > 如何将大型 int 数组放入 xml 资源文件中?

问题描述

我有大量的整数常量。我想把它们放在数组中。该数组必须可以从不同的活动中访问。如果我将此数组放入 MainActivity.java 中的变量,则从子活动中访问它会出现问题。将它们放入资源(arrays.xml)是一个更大的问题——每个整数值都必须用这个“装饰”:“<item>1234</item>”。有几千个整数值。那么声明这样的数组的最佳方法是什么?

标签: android

解决方案


您可以在一个类上创建一个私有静态不可修改的最终列表, 并拥有一个公共 getter(并且没有 setter)

我认为重要的是你要两者兼而有之finalunmodifiable如果它要保持常量,你不希望任何东西能够改变列表本身或其任何值

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);
  }
}

推荐阅读