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"/>
1

2 Answers 2

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.

Sign up to request clarification or add additional context in comments.

4 Comments

I tried this code but I get errors that I cannot resolve symbols random, textview, and nextInt
this is just snippet example now you have to pass your textview variable to it. and random and nextint should work why it is giving you cannot resolve error?
I imported import java.util.Random;
But I'm still confused as to where I have to import my textview variable. Thanks!
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]

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.