Render random image in android

Recently I have been working on android app that supposed to display random card image from set of 22 images.  To simplify this tutorial let’s create only 3 images.
Let’s create an array resource that will store reference to our images in resource/drawable  folder.


<?xml version="1.0" encoding="utf-8"?>
    <array name="cardImages">


         To find more visit:  Official android reference

As you can see we have 3 images stored in an array.
Now create new Activity and call it
    public void onCreate(Bundle savedInstanceState) {

       ImageView BackCard = (ImageView) findViewById(;

              BackCard.setOnClickListener(new OnClickListener() {
                            public void onClick(View v) {
                                // TODO Auto-generated method stub
                                BackCard.postDelayed(new Runnable() {
                                    public void run() {
                                        // TODO Auto-generated method stub
                                        // Randomly choose card
                                        int randomCard = randomCard();
                                }, 150);


   public int randomCard()
        Resources res = getResources();
        TypedArray cards = res.obtainTypedArray(R.array.cardImages);
        int randomNumber =  (int)(Math.random() * ((2 - 0) + 1));
        int card = cards.getResourceId(randomNumber, randomNumber);
        return card;

Now some explanation. I used postDelayed method, simply saying do something after time elapsed(in our case 150ms). Image backblur will be loaded for 150ms and then our actual card is displayed.

randomCard method returns int value of Image resource as setImageResource expects it.

We want to generate number from 0 to 2 where 0 is first element of our array.

Good explanation of random number generator in Java can be found here :


  1. How would I implement this so: When the user clicks a "random" button it would then randomly display an image from within the array however it cannot display the same image twice in a row.


Post a Comment