Search code examples
androidmain-activity

Importing multiple images in Android application


How can I import multiple images on my Android app? Can I assign single id to that bundle of images to bring it from drawable? Suggest me a way.

Currently I am only able to display one image multiple times in line layout. Here is the code line to bring the image:

  placeholder = BitmapFactory.decodeResource(getResources(), R.drawable.picture2);  

Should I enter multiple lines for picture3,picture4,...etc?


Solution

  • Simplest way I can think of:

    int ids[] = new int[] {
        R.drawable.picture2,
        R.drawable.picture3,
        R.drawable.picture4
    };
    
    Bitmap bitmaps[] = new Bitmap[ids.length];
    
    for(int i = 0; i < ids.length; i += 1){
        bitmaps[i] = BitmapFactory.decodeResource(getResources(), ids[i]);  
    }
    

    Also you can re-write it as a function for improving modularity.

    public Bitmap[] loadBitmaps(int ids[]){
        Bitmap bitmaps[] = new Bitmap[ids.length];
    
        for(int i = 0; i < ids.length; i += 1){
            bitmaps[i] = BitmapFactory.decodeResource(getResources(), ids[i]);  
        }
    
        return bitmaps;
    }