1

How can I reference TextView by using its id in a String variable, like:

xml file:

<TextView
    android:id="@+id/hello1"
    android:layout_width="wrap_content"
    android:layout_height="wrap_content"
    android:text=""
    />
<TextView
    android:id="@+id/hello2"
    android:layout_width="wrap_content"
    android:layout_height="wrap_content"
    android:text=""
    />

code:

 public void changetext(String z){
    String x ="R.id.hello"+z;
    TextView y = (TextView) findViewById(x);
    y.setText("I've changed");
}
kalebora
  • 111
  • 1
  • 1
  • 9

3 Answers3

2

Change your code to

public void changeText(String z){
    String x = "hello" + z;
    int id = getResources().getIdentifier(x, "id", getPackageName());
    TextView y = (TextView) findViewById(id);
    y.setText("I've changed");
}
Vladimir Petrakovich
  • 4,184
  • 1
  • 30
  • 46
0

The problem comes from your public void changetext(String z) method. Change to:

public void changeText(Activity a, int textViewId, String text) {
    TextView tv = (TextView) a.findViewById(textViewId);
    String x = "Hello:" + text; // or you can write "String x = text;" only if needed.
    tv.setText(x);
}

Here's how to use above method:

changeText(MyCurrentActivity.this, R.id.hello1, "Hi, this is my text.");

And the output will looks like this:

Hello: Hi, this is my text.

Anggrayudi H
  • 14,977
  • 11
  • 54
  • 87
0

Define two variables of textviews

TextView txt1 = findViewById(R.id.txt_one);
TextView txt2 = findViewById(R.id.txt_two);         
setTextOnTextView("Good morning", txt1);

Method will settext on textview which you have passed to method

private void setTextOnTextView(String text, TextView txtView){
        String x ="Hello My Text"+" "+text;
        txtView.setText("I've changed");
}
Hiren Patel
  • 52,124
  • 21
  • 173
  • 151