2

I have a problem with ids on Java for Android. I do some TextView by code, and give it an id. But I can't get the TextView with the id I gave it.

I tried to do this, but it's wont work.

LinearLayout ll;
int id = 2000000;
private void init() {
    ll = findViewById(R.id.layout);
}
private TextView addTV(int x, int y, int width, int height) {
    TextView tv = new TextView(this);
    tv.setId(id);
    id++;
    tv.setText("Hello");
    return tv;
}
private void changeTextTV(int id, String text) {
    TextView tv = findViewById(id); //<- this is wrong, but I don't know what is right
    tv.setText(text);
}
init();
ll.addView(addTV(0,0,100,100));
changeTextTV(2000000, "It's me");

Could you help me ?

PS : I'm French, so sorry for my spelling mistakes

Tim Fav
  • 21
  • 5
  • did you add the textview to the screen? paste your `addTv()` code – Avital May 02 '22 at 06:32
  • The ID numbers are generated at compile-time, I would not try to generate IDs at run-time. Instead simply save the references of the generated TextView instances into a field. – Robert May 02 '22 at 09:46
  • @Avital I edit my code, to add the TextView to the screen. But I don't understand why you would like the code to add the TextView to the screen. Because my question is about : How get the TextView by ID which I give it . – Tim Fav May 03 '22 at 16:52
  • your code works for me, so... – Avital May 04 '22 at 10:28

2 Answers2

1

The documentation for findViewById says that it:

Finds the first descendant view with the given ID, the view itself if the ID matches getId(), or null if the ID is invalid (< 0) or there is no matching view in the hierarchy.

with emphasis added to "descendant view." I think the issue is that you're creating a TextView but you're leaving them dangling - they're not added to the LinearLayout and then, because they're not added to the hierarchy, you fail to find them when you look for them. Consider the following:

private TextView addTV(int x, int y, int width, int height) {
    TextView tv = new TextView(this);
    tv.setId(id);
    id++;
    tv.setText("Hello");
    ll.addView(tv);   // <--- This is the change
    return tv;
}

This is a reference to the answer found here.

Chuck
  • 1,977
  • 1
  • 17
  • 23
0

after long time search and do more test. I find some answer, you have 2 choise to get the component by a setted ID :

if you want by a hard ID :

@SuppressLint("ResourceType")
private void changeTextTV(String text) {
    TextView tv = findViewById(2000000);
    tv.setText(text);
}

or by a variable

private void changeTextTV(int id, String text) {
    TextView tv = findViewById(id);
    tv.setText(text);
}

Thanks for the time you spend for me.

Tim Fav
  • 21
  • 5