10

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

mustaccio
  • 18,234
  • 16
  • 48
  • 57
MarTic
  • 665
  • 3
  • 10
  • 27

1 Answers1

25

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);
Community
  • 1
  • 1
burmat
  • 2,548
  • 1
  • 23
  • 28
  • 1
    I think the question asker explicitly does NOT want to use the XML: "how create R.id.some_id programmatically without set it in XML file" – RvdK Feb 28 '13 at 15:39
  • @RvdK Exactly. I understand that much but I was banking on the OG poster to read through the link I posted to understand that R.* is explicitly for resources. The section I posted was only a referral to a solution as close as it really gets to what is desired. – burmat Feb 28 '13 at 15:42
  • Mz point is, if is possible create id with v.setId(int id) than maybe is possible create R.* without XML declaration, maybe not, i search this topic several times with no accetable results. – MarTic Feb 28 '13 at 15:48
  • 2
    @user1173536 No, it is not possible. Think of your resources as hard coded. You cannot dynamically create them and they must be unique. You can only reference and use them. – burmat Feb 28 '13 at 16:26