1

From a string array (code below), I want to randomly display one of the strings in a TextView (code below), when a button is pressed (code below). Do I have to use an onClick"sendMessage" and then a random string generator? How would I do this in Java? Many thanks!

<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"/>
TikiFrance
  • 13
  • 6
  • check this link [Get random value from array](http://stackoverflow.com/questions/11600001/how-to-get-a-random-value-from-a-string-array-in-android) – Rishal Jul 22 '16 at 17:53

2 Answers2

2

Generate random number using function Random whose value should not be exceed (array length - 1) using that value get value from string array and display it in your textview.

String[] colors = getResources().getStringArray(R.array.colorArray);

Random random = new Random();

textView.setText(colors[random.nextInt(colors.length()-1)]);

hope this will help.

Note : This snippet is just an example .pass your variables in it.

KDeogharkar
  • 10,939
  • 7
  • 51
  • 95
0

You need a random number generator for the array indexes (see https://docs.oracle.com/javase/8/docs/api/java/util/Random.html)

Put an onClickListener on your Button. Then, using Random, generate a random int, which we will call randomNumber.

From there, the process is easy.

  1. Check if user has clicked the button via an onClickListener
  2. If the button is clicked, generate a random number, randomNumber, via the Random class.
  3. Display your random String by setting your EditText's text to colorArray[randomNumber]
Henry Dang
  • 106
  • 2