Android app, using a loop value to set visibilty and add data to textview?

I am creating an app that allows user to enter values and depending on the value a number of textviews are changed programmatically from gone to visible.
In the xml file there is TV!,TV2 and TV3, The user enters a couple of numbers from previous activity and these are used to set the visibility of the TV1,TV2 and TV3 textviews

Example:
            User enters 2.
Using a for loop 
        for (int i = 0; i<= userinput; i++){
          showTV = "TV"+(i);
          showTV.setVisibility(View.VISIBLE);
          showTV.setText(String.valueOf(list1.get(1)));

But I can not get the textview’s Id to be recognized using the i value

Can it be done this way or is this the wrong direction.

1 Like

It seems like you’re on the right track, but there’s a small mistake in your approach. When trying to dynamically set the visibility of TextViews based on user input, you should use the resource identifier (R.id) to access the TextViews rather than concatenating a string.

You can achieve this by creating an array of TextViews in your Java code that corresponds to the TextViews in your XML layout. Then, you can iterate through this array to set the visibility of TextViews based on the user input. Here’s a simplified example:

// Assuming you have TextViews in your XML with IDs TV1, TV2, and TV3
TextView tvArray = new TextView{findViewById(R.id.TV1), findViewById(R.id.TV2), findViewById(R.id.TV3)};

int userInput = 2; // Example user input

for (int i = 0; i <= userInput; i++) {
tvArray[i].setVisibility(View.VISIBLE);
tvArray[i].setText(String.valueOf(list1.get(i))); // Assuming list1 contains the values you want to set
}

Best Regards