Monday, February 13, 2012

Generate Random Numbers and Set a Random Resource as Background for a View in Android?


This code generates a random integer using Android's Random class, and sets a randomly selected drawable as background for a View.
Place your images into /res/drawable/ and update private int pics[] with the drawables from which you want to pick one randomly
private int pics[]=  {R.drawable.p1, R.drawable.p2, R.drawable.p3, R.drawable.p4, R.drawable.p5};
private Random rand = new Random();

public int set_rand_pic() {
    int pos = rand.nextInt(pics.length-1);
    mycard.setBackgroundResource(pics[pos]);
    return pos; 
}

1 comment:

  1. I just couldn't leave your website before telling you that I truly enjoyed the top quality info you present to your visitors? Will be back again frequently to check up on new posts.
    jantakhoj hyderabad

    ReplyDelete