I am adding multiple elements to layout in Java code. For example java coded before imageview to known layout with some layoutparams.
layout.addView(imageview, layoutparams);
I asume that I can't do it in XML because I don't know how many elements will be added (determined by user).
I need to set and know IDs to those added elements so I can refer to them later on.
What I need is something like (before adding):
imageview.setId(??);
Is this a good method to use? If so how do I use it? My main consern is that I am not sure how R.id works exactly. Can I for example make those IDs like 100001, 100002, 100003... ? Won't I override any? I will store those IDs in an list/array for use later in code.
public static int generateViewId ()
Added in API level 17 Generate a value suitable for use in setId(int). This value will not collide with ID values generated at build time by aapt for R.id.
What if it will colide during runtime because of multiple methods adding elements. Are there any sql-like transactions? BTW: Going for API17 isn't exactly what I want. Slightly over 50% of the market.
If you need to get a reference to a certain View that is added dynamically to a bunch of other similar Views, you might want to use a loop similar to the one below:
for(int i = 0; i < parent.getChildCount(): i++) {
View view = parent.getChildAt(i);
}
If you need more control than that then you may want to check out the View.setTag() method. Using this, you can create a unique tag for each View and retrieve it later on in a loop.
final ImageView imageView = (ImageView) findViewById(R.id.imageview);
imageView.setTag("I'm a tag!");
for(int i = 0; i < parent.getChildCount(): i++) {
View view = parent.getChildAt(i);
if(view != null && view.getTag() == "I'm a tag!") {
// Do something with the View
}
}
Although the code above should work, I might suggest approaching the issue from a different angle depending on what you intend to do with the Views.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With