kalebora
kalebora

Reputation: 111

Android: How to reference TextView via String variable?

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");
}

Upvotes: 1

Views: 2573

Answers (3)

Anggrayudi H
Anggrayudi H

Reputation: 15155

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.

Upvotes: 0

Hiren Patel
Hiren Patel

Reputation: 52800

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");
}

Upvotes: 0

Vladimir Petrakovich
Vladimir Petrakovich

Reputation: 4286

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");
}

Upvotes: 2

Related Questions