user5145575
user5145575

Reputation: 63

Android Studio Button command

I've created a string which is a random string from an array. The user presses a button and the function executes again, showing the user a new string from the array.

This is what I have thus far, which doesn't quite work:

String[] letters = {"s", "a"};
    String randomSad = (letters[new Random().nextInt(letters.length)]);
    tv1 = (TextView) findViewById(R.id.textview11);
    tv1.setText(randomSad);

Upvotes: 0

Views: 1119

Answers (1)

Samrat Dutta
Samrat Dutta

Reputation: 1737

Always provide the code that you have already tried. But this being a simple implementation, it should look like this :

String[] nameList = {"Sam", "Harry", "Ron"}; //Store the list as you like
int index i = 0;    

//put the correct id of the TextView from the xml file
TextView nameTextView = (TextView) findViewById(R.id.nameTextView);

//put the correct id of the Button from the xml file
Button button = (Button) findViewById(R.id.button1);

//set the OnclickListener and define what you want to happen in the onClick() method

button.setOnClickListener(new OnclickListener() {
    nameTextView.setText(nameList[index]); //set the name in the index as text
    if((index+1) >= nameList.length)
        index++; //increase the index by 1, for the next time.
    else
        index = 0; // to loop back to the first name.
});

If you want the last name to stay even if the butten is pressed again, cut out the else part.

Edit : ()After you provided the code

String[] letters = {"s", "a"};
String randomSad = (letters[new Random().nextInt(letters.length)]);
tv1 = (TextView) findViewById(R.id.textview11);
tv1.setText(randomSad);

 button.setOnClickListener(new OnclickListener() {
    randomSad = (letters[new Random().nextInt(letters.length)]);
    tv1.setText(randomSad); //set the name in the index as text
});

Upvotes: 2

Related Questions