In my app I am creating Views
- in this case an EditText
- dynamically. But every View
I add needs to have a unique id.
EditText editText = new EditText(context);
LayoutParams params = new LayoutParams(LayoutParams.MATCH_PARENT, LayoutParams.WRAP_CONTENT);
editText.setLayoutParams(params);
// Which value am I supposed to use here?
editText.setId(value);
layout.addView(editText);
I am afraid of conflicts if I assign a random value and I cannot think of any way to generate ids without the possibility of conflicts.
Please not that I know that one can define a fixed set of ids in res/values/ids.xml, but that is not what I want! I need to create the ids dynamically! I have no idea how many I need.
So is there any safe way to generate ids?
id
via code (programmatically)id
s using someView.setId(
int);
int
must be positive, but is otherwise arbitrary- it can be whatever you want (keep reading if this is frightful.)To assign id -
for(int i =0 ; i < yourIDcount ; i++){
yourView.setId(i);
}
To get id -
View.findViewById(yourView.getId());
Also,
API 17
introduced View.generateViewId()
which generates a unique ID.
Check:
how-can-i-assign-an-id-to-a-view-programmatically and android-assign-and-retrieve-ids-dynamically.
There are multiple ways you can reliably generate ids for your Views
. Some can be used to dynamically generate ids at runtime, others can be used to statically define a fixed number of ids. I will go over a few solutions in this answer.
Create a new xml file in res/values called ids.xml and add elements with the type id:
<?xml version="1.0" encoding="utf-8"?>
<resources>
<item name="name" type="id" /> <!-- Creates the id R.id.name -->
<item name="example" type="id" /> <!-- Creates the id R.id.example -->
</resources>
You can generate ids for other resources as well! Just change the type.
With API level 17 a new method was added to the View
class:
int id = View.generateViewId();
With it you can create as many ids as you need dynamically!
As @Apoorv suggested you can view the source code of generateViewId()
here. By copying the code we can use this method even before API level 17:
private static final AtomicInteger sNextGeneratedId = new AtomicInteger(1);
public static int generateViewId() {
for (; ; ) {
final int result = sNextGeneratedId.get();
// aapt-generated IDs have the high byte nonzero; clamp to the range under that.
int newValue = result + 1;
if (newValue > 0x00FFFFFF) newValue = 1; // Roll over to 1, not 0.
if (sNextGeneratedId.compareAndSet(result, newValue)) {
return result;
}
}
}
Just include it in a helper class and you are all set!
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