简体   繁体   English

如何从数字列表中随机填充多个 TextView?

[英]How to fill multiple TextViews randomly from a list of numbers?

I'm making some kind of game and want to fill 9 TextViews with numbers (1-9) like the image below:我正在制作某种游戏,并想用数字(1-9)填充 9 个 TextView,如下图所示:

在此处输入图像描述

I want the TextViews to get filled randomly every time the activity is created.我希望每次创建活动时随机填充 TextViews。 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.制作一个单独的方法来创建一个数组,并使用 Java 的 shuffle 方法来更改列表的顺序。 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).之后,使用 findById(x)。 And set the text of each box to list[i] depending on which number you would like from 1-9.并将每个框的文本设置为 list[i],具体取决于您希望从 1 到 9 中的哪个数字。 This ensures a number is not used more than once.这确保了一个数字不会被多次使用。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM