I'm making some kind of game and want to fill 9 TextViews with numbers (1-9) like the image below:
I want the TextViews to get filled randomly every time the activity is created. How can I make it work?
Make a seperate method to create an array and use Java's shuffle method to change the order of the list. Afterwards, you can assign each one by index to your text views.
import java.util.*;
public class Example {
public static void main (String[] args) {
ArrayList<Integer> list = new ArrayList<Integer>();
list.add(1);
list.add(2);
list.add(3);
list.add(4);
list.add(5);
list.add(6);
list.add(7);
list.add(8);
list.add(9);
System.out.println("Original list : " + list);
Collections.shuffle(list); // shuffling the list
System.out.println("Shuffled list : " + list);
}
}
Afterwards, use findById(x). And set the text of each box to list[i] depending on which number you would like from 1-9. This ensures a number is not used more than once.