androidlistviewandroid-imageviewandroid-drawablecustom-lists

How to use few drawable images in unlimited length of listview?


I have 3 images in drawable and as it is difficult to store huge image files in drawable for limitless length of listview, I want to use these three images for the entire listview repeatedly or randomly. For more to be clear..

  1. After submitting the 3rd data, I want to have the 1st image for the 4th data, the 2nd image for the 5th data, the 3rd image for the 6th data again and again. It lookes like..

1st image for ----------> 1st data

2nd image for ----------> 2nd data

3rd image for ----------> 3rd data

1st image for ----------> 4th data

2nd image for ----------> 5th data

3rd image for ----------> 6th data

...................................................

...................................................

1st image for ----------> 100th data

...................................................

...................................................

and so on or randomly if possible.

I think I have to use loop and necessary condition to solve this problem. But do not know how to go through. Can anyone help me to solve this with necessary code implemented?


Solution

  • Some suggestions to improve your solution.

    You can simply take the result of the mod (%) operator and use that for your index.

    images[index] = images[index % 3]; 
    

    That will return 0, 1, or 2 and get the correct image for you and you won't need to do any comparisons.

    And if you want to do random images, that's also very simple.

    First, create a new Random object, before your loop.

    Random random = new Random(); 
    

    Next, in your loop, you want to get a random value between 0, and 2. We're passing 2 as our upper bounds.

    images[index] = images[random.nextInt(2)];