【问题标题】:Integer array of resource ids returns 0资源 ID 的整数数组返回 0
【发布时间】:2017-04-09 13:28:52
【问题描述】:

我有一组存储在数组中的资源 ID。这可以在回收器视图中访问以填充图像视图。问题是当我访问数组时,返回的所有值都是 0。

// arrays.xml
<array name="array_category_icons">
    <item>@drawable/autumn</item>
    <item>@drawable/backpack</item>
</array>

// inside recycler view adapter
int[] myIcons = getActivity().getResources().getIntArray(R.array.array_category_icons);

myIcons[i] always returns 0. 

drawables 仅在 hdpi 文件夹中。

【问题讨论】:

    标签: java android xml android-drawable android-resources


    【解决方案1】:

    这样做:

    TypedArray ta = getResources().obtainTypedArray(R.array.array_category_icons);
    Drawable[] icons = new Drawable[ta.length()];
    for (int i = 0; i < ta.length(); i++) {
        int id = ta.getResourceId(i, 0);
        if (id != 0) {
            icons[i] = ContextCompat.getDrawable(this, id);
        }
    }
    ta.recycle();
    

    【讨论】:

      猜你喜欢
      • 2011-07-17
      • 1970-01-01
      • 2020-08-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2019-10-01
      相关资源
      最近更新 更多