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(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.new_layout);
LinearLayout ll = (LinearLayout)findViewById(R.id.layout);
View v = new View(this);
v.setBackgroundColor(0xFFFF0000);
ll.addView(v, 100, 100);
}
and I can add v.setId(50)
, but I would like add v.setId(R.id.some_id)
and I wouldn't like add some_id
into xml file, this option I know.
My question is, how to create R.id.some_id
programmatically without setting it in XML file. Thanks
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:
android:id
for use in codeIf 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);
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