当按下按钮(下面的代码)时,我想从字符串数组(下面的代码)中随机显示 TextView 中的字符串之一(下面的代码)。我是否必须使用 onClick"sendMessage"然后使用随机字符串生成器?我将如何在 Java 中做到这一点?非常感谢!
<resources>
<string-array name="colorArray">
<item>Green</item>
<item>Red</item>
<item>Purple</item>
<item>Blue</item>
<item>Orange</item>
<item>Brown</item>
<item>Yellow</item>
<item>White</item>
<item>Pink</item>
</resources>
<TextView
android:layout_width="match_parent"
android:layout_height="match_parent"
android:text="NOT SURE WHAT TO PUT HERE"
android:textSize="76sp"
android:gravity="center"
android:textAllCaps="true"/>
<Button
android:id="@+id/green_button"
android:layout_width="0dp"
android:layout_height="match_parent"
android:layout_weight="1"
android:background="@drawable/green_button"/>
最佳答案
使用函数Random
生成随机数,其值不应超过(数组长度 - 1),使用该值从字符串数组中获取值并将其显示在 TextView 中。
String[] colors = getResources().getStringArray(R.array.colorArray);
Random random = new Random();
textView.setText(colors[random.nextInt(colors.length()-1)]);
希望这会有所帮助。
注意:此代码 fragment 只是一个示例。在其中传递您的变量。
关于java - 按下按钮时显示数组中的随机文本,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/38532507/