TextView 中的白屏

White screen in TextView

我是 Android 的初学者。我想在 TextView 中打印它,但屏幕全是白色,我看不到 TextView 的内容。在控制台中工作正常。下面是我的 activity 和布局文件。

public class MainActivity extends AppCompatActivity {
TextView textView;
@Override
protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.activity_main);

 Fruits();


}

public void Fruits() {

    textView= findViewById(R.id.pa);


    String[] fruit = {"orange", "apple", "pear", "bannana", "strawberry", "mango","grape","lemon"};
    Random numberGenerator = new Random();
    /* Generate A Random Number */
    int nextRandom = numberGenerator.nextInt(fruit.length)
    ;
    Set<Integer> validate = new HashSet<>();
    /* Add First Randomly Genrated Number To Set */
    validate.add(nextRandom);
    for (int i = 0; i < fruit.length; i++) {
        /* Generate Randoms Till You Find A Unique Random Number */
        while(validate.contains(nextRandom)) {
            nextRandom = numberGenerator.nextInt(fruit.length);
        }
        /* Add Newly Found Random Number To Validate */
        validate.add(nextRandom);
        System.out.println(fruit[nextRandom]);
        textView.setText(fruit[nextRandom]);


    }


}
}

布局

      <TextView
        android:id="@+id/pa"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:text="Hello World!"
        app:layout_constraintBottom_toBottomOf="parent"
        app:layout_constraintLeft_toLeftOf="parent"
        app:layout_constraintRight_toRightOf="parent"
        app:layout_constraintTop_toTopOf="parent" />

while 循环将永远重复。 当i等于fruit.length-1时,validate已经存储了[0,fruit.length)范围内的数,导致while循环中的条件一直为真,程序出不来循环导致您在 while 循环内生成的 nextNumber 始终在 [0,fruit.length) 范围内。为简单起见,假设 fruit 数组只有一个元素。

您的 while 循环是一个无限循环,因为验证集将在一个点上包含所有 8 个值,并且始终为真。因此,您的 textView 永远不会设置,并且会一次又一次地设置。

在 while 循环中添加对集合大小的额外检查:

 for (int i = 0; i < fruit.length; i++) {
            /* Generate Randoms Till You Find A Unique Random Number */
            while(validate.size() != fruit.length && validate.contains(nextRandom)) {
                nextRandom = numberGenerator.nextInt(fruit.length);
            }
            /* Add Newly Found Random Number To Validate */
            validate.add(nextRandom);
           Log.i("HELLO",fruit[nextRandom]);
            textView.setText(fruit[nextRandom]);
        }

以上将打印随机采摘的水果,一旦验证已满将跳过。

注意:我添加了一个额外的集合大小检查(仅作为示例),您可以添加您必须退出循环的断点。