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");
}
4
  • findViewById takes a resource a id which is an int value Commented Jan 23, 2015 at 2:55
  • Duplicate question! Commented Jan 23, 2015 at 2:57
  • for more info check the source androidxref.com/5.0.0_r2/xref/frameworks/base/core/java/android/… Commented Jan 23, 2015 at 2:57
  • 1
    What is your main goal? What can we help you figure out? Commented Jan 23, 2015 at 3:24

3 Answers 3

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");
}
Sign up to request clarification or add additional context in comments.

Comments

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

Comments

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.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.