簡體   English   中英

Android訪問drawable文件夾

[英]Android accessing drawable folder

我在可繪制文件夾中放置了10個圖像,然后創建了一個自定義類,其中實例持有一個id Integer,它應該將它引用到draw文件夾中的圖像。 現在我想知道如何設置這些id-s,而不是一個一個。 代替:

object[0].setImage(R.drawable.image1);
object[1].setImage(R.drawable.image2);

我想用循環做這個,但是怎么樣?

已知的可Drawable id在final class R靜態類中生成。 因此,只需使用反射來讀取這些靜態屬性的值。 如果您想獲取Int ID,請使用以下代碼:

    for(Field f : R.drawable.class.getDeclaredFields()){
        if(f.getType() == int.class){
            try {
                   int id = f.getInt(null);
                   // read the image from the id
            } catch (IllegalAccessException e) {
               e.printStackTrace();
            } catch (IllegalArgumentException e){
                e.printStackTrace();
            }
        }
    }

或者,如果您想直接按圖像的名稱進行搜索,您可能會對以下字段的name屬性感興趣:

    for(Field f : R.drawable.class.getDeclaredFields()){
        if(f.getType() == int.class){
            try {
                String name = f.getName();
                // rest of the code handling file loading
                } catch (IllegalAccessException e) {
                e.printStackTrace();
            } catch (IllegalArgumentException e) {
                e.printStackTrace();
            }
        }
    }

就我認為不起作用。

有代碼可以通過名稱獲得drawable。 例如: "image"+myNumber"

也許: 如何在android中按名稱訪問可繪制資源

請注意,視圖列表的大小應與保存ID的大小相匹配:

public class HolderIDs {

public List<Integer> _ids;

public HolderIDs() {
    _ids = new ArrayList<Integer>(Arrays.asList(R.drawable.one, R.drawable.two, R.ldrawable.three, R.drawable.four));
}

public List<Integer> getIDs() {
    return _ids;
}

}

//用法

List<ImageView> views = getYourViews();

List<Integer> ids = new HolderIDs().getIDs();

for (int i = 0; i < ids.size(); i++) {
    View view = views.get(i);
    if (view == null) return;
    int id = ids.get(i);
    view.setBackgroundResource(id);
}

您可以為資源創建整數數組:

int resources = [R.drawable.image1,R.drawable.image2,...]

並使用bucle將資源設置為對象數組。

暫無
暫無

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

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