Skip to content Skip to sidebar Skip to footer

Android Create ID Programmatically

I am looking for creating ID in code without using XML declaration. For example, I have code, where I programmatically create View like this @Override protected void onCreate(Bundl

Solution 1:

Refer to this fantastic answer: https://stackoverflow.com/a/13241629/586859

R.* references are used explicitly to access resources. What you are trying to do is not really possible, but maybe you could us something like the following section from the above answer:

Reserve an XML android:id for use in code

If your ViewGroup cannot be defined via XML (or you don't want it to be) you can reserve the id via XML to ensure it remains unique:

Here, values/ids.xml defines a custom id:

<?xml version="1.0" encoding="utf-8"?>
<resources>
    <item name="reservedNamedId" type="id"/>
</resources>

Then once the ViewGroup or View has been created, you can attach the custom id

myViewGroup.setId(R.id.reservedNamedId);

Post a Comment for "Android Create ID Programmatically"