我想从一个字符串数组(下面的代码)中,当按下一个按钮(下面的代码)时在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)]);
希望这会有所帮助。
注意:此代码段只是一个示例。在其中传递变量。
本文收集自互联网,转载请注明来源。
如有侵权,请联系[email protected] 删除。
我来说两句