Skip to content Skip to sidebar Skip to footer

Random Text On Button Click

I have around 150 different texts that I want to be shown in random order when I press a Button. A new one every time I press the Button. I have figured out this code: Random my

Solution 1:

Your onClickListener has no context from which to call findViewById(). I would probably instead use the design pattern where your activity implements the click listener. Read http://android-developers.blogspot.com/2009/10/ui-framework-changes-in-android-16.html and search for "Easier click listeners".

Solution 2:

You have to add a Listener to your button.

textblondin.setOnClickListener(new View.OnClickListener() {
    ... yourcodehere ...
}

Solution 3:

In the Android Docs you can find how to execute code on a button click.

http://developer.android.com/reference/android/widget/Button.html

Solution 4:

store the all 150 strings in an Arraylist and display the text by randomly generated number.

samples;

ArrayList<String> arr_str = new ArrayList<String>();

arr_str.add(String Parameter) // add the all strings in arraylist by using the method.

Random randomGenerator = new Random();
int randomInt = 0;

within  the button onclick listener write the following code.
{
  randomInt = randomGenerator.nextInt(149);  // this will generate random number b/w 0 to 149.
textView.setText(arr_str.get(randomInt));  // you can get the n th number of string stored in the arraylist.
} 

Post a Comment for "Random Text On Button Click"