Android Random

String rank[] = {"tclub1.png", "tclub2.png", "tclub3.png", "tclub4.png",
  "tclub5.png", "tclub6.png", "tclub7.png", "tclub8.png", "tclub9.png",
  "tclub10.png", "tclub11.png", "tclub12.png", "tclub13.png"};

Random randInt = new Random();
int b = randInt.nextInt(rank.length);
String d = ("tclub" + b + ".png");
Log.v(LOG_TAG, "in value:=" + d);

Above is the code. Actually my array gives me one random index between (from 0 to 12) .. after that I add it to create the image name. for example (tclub1.png) Now the name of the image that he gives me is String fromat. how can i assign this image now randomly?

+3
source share
2 answers

If you want to upload an image to ImageView, you can do this:

String imgName = "tclub1"; // the image you want to load
int id = getResources().getIdentifier(imgName, "drawable", getPackageName());  
imageView.setImageResource(id); 
+1
source

to find the control:

ImageView image = (ImageView) findViewById(R.id.rockId);

To dynamically load an image from drawable, I use this helper function

public static int getDrawable(Context context, String name)
{
    Assert.assertNotNull(context);
    Assert.assertNotNull(name);

    return context.getResources().getIdentifier(name,
            "drawable", context.getPackageName());
}

this will return the identifier of your resource, now all you need is to set the image in the control:

image.setImageResource(int Id);
0

Source: https://habr.com/ru/post/1756150/


All Articles