在 Android 中迭代可绘制对象

Iterating over drawables in Android

在 Android 中,我只找到了关于如何从 MainActivity.java 打开 单个特定 Drawable 的答案,但没有找到如何打开的答案从 res/drawables 迭代每个 DrawableDrawable 的名称不遵循任何模式(例如从 0 到 25 编号),因此建议 here 的答案遗憾地没有解决我的问题。有谁知道后者该怎么做?

提前谢谢你:)

首先,将您的可绘制对象放入数组中

<array name="dashboard_item_menu_drawable">
    <item>@drawable/ic_file_green</item>
    <item>@drawable/ic_email_green</item>
    <item>@drawable/ic_linear_scale_green</item>
    <item>@drawable/ic_undo_green</item>
    <item>@drawable/ic_check_circle_green</item>
    <item>@drawable/ic_archive_green</item>
</array>

然后,迭代您的数组 drawables

val icons = ArrayList<Int>()
val arr = resources.obtainTypedArray(R.array.dashboard_item_menu_drawable)
(0 until arr.length()).forEach {
    // get resource id of each drawable
    val icon = arr.getResourceId(it, -1)
    icons.add(icon)
}

接下来,回收资源

arr.recycle()

然后你就可以使用你的drawable

iconView.setImageDrawable(ContextCompat.getDrawable(this, icons[index]))

如果您想遍历名称相似的可绘制对象,例如:image1、image2、...、image10,您可以这样做:

    for (int i = 0; i < 10; i++) {
        int id = getResources().getIdentifier("image" + i, "drawable", getPackageName());
        Drawable d = ContextCompat.getDrawable(this, id);
        // your code here
    }

最简单的方法是将可绘制对象的名称放入字符串数组中:

String[] symbols = {"first_img", "second_img", "third_img", "fourth_img"};

然后像这样遍历它们(我将图像放入 GridLayout 中):

for(String symbol : symbols) {
    int id = getResources().getIdentifier(symbol, "drawable", getPackageName());

    ImageView img = new ImageView(this);
    LinearLayout.LayoutParams imgParams = new LinearLayout.LayoutParams(300, 300);
    imgParams.setMargins(30, 30, 30, 30);
    img.setLayoutParams(imgParams);
    img.setBackgroundResource(id);
    symbolGrid.addView(img);
}