簡體   English   中英

迭代 Android 中的可繪制對象

[英]Iterating over drawables in Android

在 Android 中,我只找到了有關如何從MainActivity.java打開單個特定Drawable答案,但沒有找到如何從res/drawables迭代每個Drawable答案。 Drawable的名稱不遵循任何模式(例如編號從 0 到 25),因此很遺憾這里建議的答案並沒有解決我的問題。 有誰知道如何做后者?

先感謝您 :)

首先,將您的可繪制對象放入數組中

<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>

然后,迭代您的數組可繪制對象

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 數組中:

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);
}

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM