I'm trying to an android version of an iOS app I recently launched. I'm struggling with image array. In iOS, add my image files, then call them by creating a var = UIImage(named:"name image file), then I use that. In Android, I don't know how to access the drawable folder to make an image array that has multiple images, and how to call it in code so it is displayed in the image view on the screen. I tried but had so many errors. Not many answers on the Net as well, been trying for two days. For now, I am thinking of a button and an image view on the screen/activity. When I press the button, a random image appears. Could you please tell me how to go about it? (I took a Kotlin course on Treehouse but they only do an array of strings, I used that as a base but just don't know how to work with multiple images at all). Appreciate your help, thanks.
1 Answer
used below code ..
var cards= arrayOf(R.drawable.card1,R.drawable.card2,R.drawable.card3,R.drawable.card4,R.drawable.card5,R.drawable.card6,R.drawable.card7);
button.setOnClickListener {
var r = new Random()
var n=r.nextInt(7)
imageview.setImageResource(cards[n]);
}
1 Comment
learningguru
Thanks a lot @Android Team, it worked (without the new pin Random), but took a long time to run, threw this error (error: class R is public, should be declared in a file named R.java), when I double clicked it seems to have opened an R file with an empty class. I have 108 images, should I create a separate class or Kotlin file to hold the array? How do I call in Main Activity? Thanks for your patience, appreciate it.