I have a dynamically created View and want to find it by tag, is this possible?
I know the function findViewById
, is there something similar for tags?
Asked
Active
Viewed 3.9k times
20

BillHaggerty
- 6,157
- 10
- 35
- 68

BenG
- 401
- 4
- 7
- 15
-
2yes, there is findViewWithTag – Marko Niciforovic Jun 09 '14 at 08:06
-
1Of course, you should set tag for your view first :D – kidnan1991 Jun 09 '14 at 08:37
3 Answers
23
LinearLayout linLayout = (LinearLayout)findViewWithTag("layout1");
but I don't think you need tag for dynamic view. You can retrieve dynamic resource by following code
for (int i=0; i < total_resource; i++) {
//retrieve id dynamically
int id = getResources().getIdentifier("resource"+i, "id", getPackageName());
TextView myText = (TextView) findViewById(id); // get the element
}

Cœur
- 37,241
- 25
- 195
- 267

user3384985
- 2,975
- 6
- 26
- 42
-
2You don't need it but it's extremely handy for dinamycally generated views that are to be updated from external services – Caterpillaraoz Sep 10 '19 at 09:52
2
Create ids.xml to store your id:
<?xml version="1.0" encoding="utf-8"?> <resources> <item type="id" name="component1" /> <item type="id" name="component2" /> <item type="id" name="component3" /> </resources>
Set to dynamically created component like:
Button1.setId(R.id.layout1); buttom2.setId(R.id.layout2); button3.setId(R.id.layout3);
Another way is to set a tag to your component while creating dynamically
button1.setTag(1);
And use getTag()
to get that component
2
You can find by tag inside other view.
Say, you have LinearLayout with several buttons that you dynamically put inside it and assigned tag for each of them. You MUST know id for that LinearLayout b/c 1st your find it by id. Then find buttons by tag inside that LinearLayout view:
LinearLayout ll=(LinearLayout)findViewById(R.id.mylinearlayout);
Button btn= (Button)ll.findViewWithTag("mybtntag");//tag must be string

Boris Gafurov
- 1,427
- 16
- 28