Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Android create ID programmatically [duplicate]

Tags:

java

android

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

like image 652
user1173536 Avatar asked Feb 28 '13 15:02

user1173536


1 Answers

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);
like image 115
burmat Avatar answered Nov 09 '22 09:11

burmat