牛骨文教育服务平台(让学习变的简单)
博文笔记

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

创建时间:2014-07-07 投稿人: 浏览次数:2708

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

xml数组定义:

   <array name="category_default">
        <item>@array/category_default_title</item>
        <item>@array/category_default_background</item>
        <item>@array/category_default_cover</item>
    </array>
    <array name="category_default_title">
        <item>@string/category_myshelf</item>
        <item>@string/category_myread</item>
        <item>@string/category_doctor</item>
        <item>@string/category_master</item>
        <item>@string/category_courseteam</item>
        <item>@string/category_userspace</item>
    </array>
    <array name="category_default_background">
        <item>@color/purple_af</item>
        <item>@color/green_8c</item>
        <item>@color/blue_59</item>
        <item>@color/pink_f6</item>
        <item>@color/yellow_fb</item>
        <item>@color/red_fc</item>
    </array>
    <array name="category_default_cover">
        <item>@drawable/category_myshelf_s</item>
        <item>@drawable/category_myread_s</item>
        <item>@drawable/category_doctor_s</item>
        <item>@drawable/category_doctor_s</item>
        <item>@drawable/category_courseteam_s</item>
        <item>@drawable/category_userspace_s</item>
    </array>

以上定义了二维数组“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<Category> categoryList = new ArrayList<Category>();
  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

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

声明:该文观点仅代表作者本人,牛骨文系教育信息发布平台,牛骨文仅提供信息存储空间服务。