当前位置: 首页 > 工具软件 > xml2array() > 使用案例 >

android arrays.xml 二维数组,android 读取array.xml 中String、int、drawable等数组及多维的方法...

卢英叡
2023-12-01

从array.xml 中读取String、int、drawable等数组/多维数组

xml数组定义:

@array/category_default_title

@array/category_default_background

@array/category_default_cover

@string/category_myshelf

@string/category_myread

@string/category_doctor

@string/category_master

@string/category_courseteam

@string/category_userspace

@color/purple_af

@color/green_8c

@color/blue_59

@color/pink_f6

@color/yellow_fb

@color/red_fc

@drawable/category_myshelf_s

@drawable/category_myread_s

@drawable/category_doctor_s

@drawable/category_doctor_s

@drawable/category_courseteam_s

@drawable/category_userspace_s

以上定义了二维数组“category_default”,和一维数组“category_default_title”、“category_default_background”、“category_default_cover”,数组中的内容在string、color和drawable中定义好了

读取数组:

private void init() {

//obtain the referenced arrays

TypedArray cateDefaultArray = getResources().obtainTypedArray(R.array.category_default);//读取二维数组

String[] categoryTitleArray = getResources().getStringArray(cateDefaultArray.getResourceId(0, -1));//读取string数组

int[] categoryBgArray = getResources().getIntArray(cateDefaultArray.getResourceId(1, -1));//读取int数组

TypedArray categoryCoverArray = getResources().obtainTypedArray(cateDefaultArray.getResourceId(2, -1));//读取drawable数组

cateDefaultArray.recycle();

ArrayList categoryList = new ArrayList();

for (int i = 0; i < categoryTitleArray.length; i++) {

Category temp = new Category();

temp.setTitle(categoryTitleArray[i]);

System.out.println("category:title="+temp.getTitle());

temp.setColor(categoryBgArray[i]);

System.out.println("category:color="+temp.getColor());

temp.setId(categoryCoverArray.getResourceId(i, -1));

System.out.println("category:id="+temp.getId());

categoryList.add(temp);

}

categoryCoverArray.recycle();

}

打印结果:

category:title=书架

category:color=-5271617

category:id=2130837668

category:title=论文

category:color=-7548558

category:id=2130837666

category:title=文献

category:color=-10897954

category:id=2130837663

category:title=资源

category:color=-624192

category:id=2130837663

category:title=团队

category:color=-276124

category:id=2130837661

category:title=空间

category:color=-237718

category:id=2130837670

以上是项目中的一个方法,绝对可用

由于读取drawable数组的方法一直没找到,困扰了一天,今天终于找到了解决方法所以发出来和大家分享

 类似资料: