lundi 7 septembre 2015

How do I randomize images in android studio? The code I wrote isn't working

I want to randomize the the back images that will be brought from a database(code still not added), but the code I wrote isn't working. I have originally just added the flip function. I searched up how to randomize images and tried to follow the code given. Sadly its not working for me.

protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.activity_main);

    // get references to the imageView objects
    imgUpperLeft = (ImageView) findViewById(R.id.imgUpperLeft);
    imgUpperRight = (ImageView) findViewById(R.id.imageView2);
    imgLowerLeft = (ImageView) findViewById(R.id.imageView3);
    imgLowerRight = (ImageView) findViewById(R.id.imageView4);

    // Setting the initial image (First face of cards)
    imgUpperLeft.setImageResource(R.drawable.img_waterfall);
    imgUpperRight.setImageResource(R.drawable.img_waterfall);
    imgLowerLeft.setImageResource(R.drawable.img_waterfall);
    imgLowerRight.setImageResource(R.drawable.img_waterfall);

    imgUpperLeft.setVisibility(View.VISIBLE);
    imgUpperRight.setVisibility(View.VISIBLE);
    imgLowerLeft.setVisibility(View.VISIBLE);
    imgLowerRight.setVisibility(View.VISIBLE);


}


ImageView imgView = new ImageView(this);
Random rand = new Random();
int rndInt = rand.nextInt(4) + 1; // n = the number of images, that start at idx 1
String imgName = "img" + rndInt;
int id = getResources().getIdentifier(imgName, "drawable", getPackageName());

// Shows the second face of the cards

public void showUpperLeftImage(View v){
    imgView.setImageResource(id);
}
public void showUpperRightImage(View v){
    imgView.setImageResource(id);
}
public void showLowerLeftImage(View v){

    imgView.setImageResource(id);
}
public void showLowerRightImage(View v){
    imgView.setImageResource(id);
}




Aucun commentaire:

Enregistrer un commentaire