Welcome to the Treehouse Community
Want to collaborate on code errors? Have bugs you need feedback on? Looking for an extra set of eyes on your latest project? Get support with fellow developers, designers, and programmers of all backgrounds and skill levels here with the Treehouse Community! While you're at it, check out some resources Treehouse students have shared here.
Looking to learn something new?
Treehouse offers a seven day free trial for new students. Get access to thousands of hours of content and join thousands of Treehouse students and alumni in the community today.
Start your free trial
Gábor Rácz
4,201 PointsRandomly generate images via an array with an OnClickListener
I'm trying to get images to randomly appear through the drawable file after clicking a button.
In the MainActivity class I created an ImageView for the images. Then within the OnClickListener constructor, I notated the images to 'setImageResource'. I'm trying to mimic the function of an array when the button is clicked. It worked briefly, after having only 2 images. Adding 2 more images crashes the app. Not sure why ... ?
What would the correct procedure be in creating an array of images and calling them to execute this type of procedure?
//The Code Below
@Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.activity_divination);
final TextView cardVersionTitle; //telling myself the version of my app - hardcoded
final Button showCardButton;
final EditText cardTextView; //hardcoded instructions - ie: "Click the button to play"
final ImageView image1;
final ImageView image2;
final ImageView image3;
final ImageView image4;
cardVersionTitle = (TextView) findViewById(R.id.cardVersionTitle);
showCardButton = (Button) findViewById(R.id.showCardButton);
cardTextView = (EditText) findViewById(R.id.cardTextView);
image1 = (ImageView) findViewById(R.id.imageView1);
image2 = (ImageView) findViewById(R.id.imageView2);
image3 = (ImageView) findViewById(R.id.imageView3);
image4 = (ImageView) findViewById(R.id.imageView4);
View.OnClickListener listener = new View.OnClickListener()
{
@Override
public void onClick(View v)
{
//button clicked, update card image with a new image
image1.setImageResource(R.drawable.image1);
image2.setImageResource(R.drawable.image2);
image3.setImageResource(R.drawable.image3);
image4.setImageResource(R.drawable.image4);
}
};
showCardButton.setOnClickListener(listener);
<<Please excuse the messy code. I'm trying to wrap my head around it all ...>> Thanks!