It is impossible to change the name of a variable in runtime. Variables are tools you use as a developer to tell the "computer" what you want it to do. This question is as invalid as asking if you can write code that removes the need of adding a semicolon (;
) at the end of every statement. Variable names are just names you call certain elements you're working with. This is simply how Java works.
That being said, what you're trying to do can be achieved by using a simple array, and iterating over it. Here's how you can do it:
TextView[] textViews = new TextView[] { textView1, textView2, textView3, textView4 };
for (int i = 0; i < textViews.length; i++)
{
textViews[i].setText("some text");
}
Here, you create a new variable called "textViews
", which is a TextView
type array. Within it, you have 4 references to other TextViews
, each defined by the variable name you gave it previously.
EDIT:
If your TextViews
are defined in the XML layout file, then you can either initialise the textView1, textView2, .. variables prior to creating the array, or you could initialise the array directly with calls to findViewById
, like so:
TextView[] textViews = new TextView[] {
(TextView)findViewById(R.id.textView1),
(TextView)findViewById(R.id.textView2),
(TextView)findViewById(R.id.textView3),
(TextView)findViewById(R.id.textView4)
};