Hello, in my quiz app, I store questions and answers in two text files. Is it possible to create an array with pictures (one per question) so that it is tied to one ImageView?
- The question is not clear. What does "an array of images associated with ImageView" mean? - Yuriy SPb ♦
- One ImageView in the markup and in the code, just change the contents of it - vitidev
- pictures from the array should display one ImageView in the xml file - A.Schtolc
- @ A.Schtolc, do you want to periodically change the image in ImageVeiw or display it all at once in one ImageView? Your question is still not clear. - Yuriy SPb ♦
- @Yuriy SPb, I wanted the image to change periodically in the ImageView - A.Schtolc
|
1 answer
Your question consists of several parts:
- How to run some code with a certain frequency?
- How to assign a picture in ImageView from an array of pictures.
The first is that you can do it very differently. For example, through Timer and TimerTask something like this:
Timer timer; TimerTask timerTask; timer = new Timer(); timerTask = new TimerTask() { @Override public void run() { runOnUiThread(new Runnable() { @Override public void run() { //код здесь выполнится раз в 5000мс //именно тут можно поменять картинку в ImageView (см. далее ответ) } }); } }; timer.schedule(timerTask, 0, 5000); The second is to first create an array with, for example, the int values of the ID-Swords of pictures from the R class, i.e. those that are in the res/drawable
int[] imgsArray = new int[]{R.drawable.ic_launcher, R.drawable.another_img, R.drawable.another_img_1}; //например генерируем случайное число и устанавливаем в ImageView картинку, извелекая её ID из массива по случайному индексу Random rnd = new Random(); int index = rnd.nextInt(imgsArray.lenght); int randomImgId = imgsArray[index]; ImageView iv = ...; iv.setImageResource(randomImgId); Now, actually, by placing the second piece of code instead of a comment in the first, you will get a random picture from the array, which will change every 5s
|