0

I'm programming with Android Studio and trying to program a scissors rock paper game. Now I'm programming a highscore where the users can see there records as list of 10 elements.

To insert the name of the players in this List I insert the values in the Textview with:

TextView tempField = findViewById(R.id.playerName1);
tempField.setText(sharedpreferences.getString("name" + i, ""));

Because these are 10 elements and I need to insert 3 values for every element I would like to do this with a for-loop. The problem is that I can't just put a variable with the number after R.id.playerName. I tried:

for(int i = 0; i < 10; i++){
   TextView tempField = findViewById("R.id.playerName" + i);
   tempField.setText(sharedpreferences.getString("name" + i, ""));
}
  • 1
    This might help you https://stackoverflow.com/questions/2941459/how-do-i-iterate-through-the-id-properties-of-r-java-class – user8225639 Jun 16 '20 at 17:55

1 Answers1

0

You can create an array of any object, you just need to iterate through the array with a loop to assign their attributes.

To set up an example, let's look at some things:

From what I understand, you have 3 different values you need to set for each TextView. I'm assuming you're looking for a format similar to X: Name - Score. I would use a for loop to set three different arrays so your values are local, but also so it makes it easier for you to use them in another loop if you haven't already.

After having that, I would set it up with something like this:

TextView[] myTextViews = new TextView[10];

for (int tv = 0; tv < 10; tv++){

    myTextViews[tv] = new TextView(this);
    myTextViews[tv].setText(array1[tv] + ": Name:" + array2[tv] + "- Score:" array3[tv]); //per the format I mentioned above.
    parentView.addView(myTextViews[tv]);

}

Where array1, array2, and array3 are the 3 values you mentioned in your question.

This way you initialize each TextView and it's attributes in each iteration. You can put this in a method so you can update it every time a new game is created, etc etc.

Ethan Moore
  • 383
  • 1
  • 5
  • 18