Reputation: 21
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
Upvotes: 2
Views: 65
Reputation: 21
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.
Upvotes: 0
Reputation: 2102
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.
Upvotes: 1