How can I assign an ID to a view programmatically?

后端 未结 3 1869
陌清茗
陌清茗 2020-11-22 07:27

In an XML file, we can assign an ID to a view like android:id=\"@+id/something\" and then call findViewById(), but when creating a view programmati

3条回答
  •  攒了一身酷
    2020-11-22 07:56

    You can just use the View.setId(integer) for this. In the XML, even though you're setting a String id, this gets converted into an integer. Due to this, you can use any (positive) Integer for the Views you add programmatically.

    According to View documentation

    The identifier does not have to be unique in this view's hierarchy. The identifier should be a positive number.

    So you can use any positive integer you like, but in this case there can be some views with equivalent id's. If you want to search for some view in hierarchy calling to setTag with some key objects may be handy.

    Credits to this answer.

提交回复
热议问题