0

Suppose I create an EditText using the following code and add it to a programmatically created LinearLayout, will it get assigned some ID or do I need to manually assign one using setId()?

I ask this question because there is no chance of Android assigning the same id to two different views whereas if we do it ourselves, something like that might happen.

        LayoutParams fparams = new LayoutParams(LayoutParams.MATCH_PARENT, LayoutParams.WRAP_CONTENT, 5.0f);
        LayoutParams tvparams = new LayoutParams(LayoutParams.WRAP_CONTENT, LayoutParams.WRAP_CONTENT);
        LayoutParams btparams = new LayoutParams(25, 25);

        first.setLayoutParams(fparams);
        first.setOrientation(LinearLayout.HORIZONTAL);

        EditText tv = new EditText(this);
        tvparams.weight = 4.97f;
        tv.setLayoutParams(tvparams);
        tv.setHint("Destination Address / Postcode");

        Button bt = new Button(this);
        bt.setBackground(getResources().getDrawable(R.drawable.minus));
        bt.setTextColor(Color.parseColor("#ffffff"));
        bt.setTextSize(12f);
        btparams.weight = 0.03f;
        bt.setLayoutParams(btparams);

        first.addView(bt);
        first.addView(tv);
        main.addView(first);
Asim
  • 6,962
  • 8
  • 38
  • 61
  • I suggest looking at [How can I assign an ID to a view programmatically?](http://stackoverflow.com/questions/8460680/how-can-i-assign-an-id-to-a-view-programmatically) – Jesper Riemer Andersen May 21 '14 at 09:03
  • Err I know how to do that. I mentioned it in my question (using view.setId()). My question is, is it automatically assigned an ID or do we need to add one manually? If manually, what would be the best way to add a randomized id that doesn't repeat (views are being added dynamically). – Asim May 21 '14 at 09:06
  • and why do you need to setId for a View that you have created by yourself? – pskink May 21 '14 at 09:10
  • It's like this.. A passenger can add multiple destinations to his ride in a cab. One is default (which is coded in the xml), then there is a button to add more layouts (and remove them). That I have done programmatically because I didn't know how else to. I need to be able to identify the view by something (hence the setId) – Asim May 21 '14 at 09:12
  • so you created a View, right? so you have the reference to that View so keep it in some field for later use – pskink May 21 '14 at 09:17

1 Answers1

1

There is a constant for views to mark them with no id View.NO_ID.

I'm not sure what you want to achieve, but new views get assigned the id View.NO_ID.

However if you want to generate IDs you can use View.generateViewId().

Edit:

Based on your comment I'm editing my answer. View.generateViewId() does not exists below API level 17, this question "how to avoid ID conflicts?" contains an answer with code to generate ids below API 17.

Community
  • 1
  • 1