如何将大型int数组放入xml资源文件中?

时间:2019-02-02 14:14:05

标签: android

我有大量的整数常量。我想将它们放在数组中。该数组必须可用于不同的活动。如果我将此数组放在MainActivity.java中的变量中,则从子活动访问它时会出现问题。将它们放入资源(arrays.xml)是一个更大的问题-每个整数值都必须使用“ 1234 ”进行“修饰”。有成千上万的整数值。那么,声明这种数组的最佳方法是什么?

2 个答案:

答案 0 :(得分:0)

您可以使用如下静态数组创建一个类:

private class MyClass {
    final static ArrayList<Integer> mylist = new ArrayList<>();

public MyClass(){
   this.mylist.add(1234);
   this.mylist.add(1284);
   ..........
 } 

 pblic ArrayList<Integer>  getmylist(){
  return this.mylist;
 }

然后在每个活动中,您需要您的列表:

MyClass myclass = new MyClass();
ArrayList<Integer> myList = myclass.getmylist();

答案 1 :(得分:0)

您可以在一个班级中创建一个私人的静态不可修改的最终列表 并有一个公共获取者(没有二传手)

我认为将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);
  }
}