Sunday, 18 November 2012

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.

array.xml

<?xml version="1.0" encoding="utf-8"?>
<resources>
    <array name="cardImages">
        <item>@drawable/death</item>
         <item>@drawable/chariot</item>
          <item>@drawable/devil</item>
     
    </array>

</resources>

         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 Card.java
 @Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.card);

       ImageView BackCard = (ImageView) findViewById(R.id.backcard);

              BackCard.setOnClickListener(new OnClickListener() {
                           
                            public void onClick(View v) {
                                // TODO Auto-generated method stub
                                BackCard.setImageResource(R.drawable.backblur);
                                BackCard.postDelayed(new Runnable() {
                                   
                                    public void run() {
                                        // TODO Auto-generated method stub
                                        // Randomly choose card
                                       
                                        int randomCard = randomCard();
                                       
                                        BackCard.setImageResource(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 : http://stackoverflow.com/questions/363681/generating-random-number-in-a-range-with-java