two views with same id

后端 未结 3 590
佛祖请我去吃肉
佛祖请我去吃肉 2020-12-03 04:32

How does android use R.id.id_name to find views after inflating the XML?

1.Suppose I have two XML\'s with one button each with same id.

2.I have

3条回答
  •  情深已故
    2020-12-03 05:30

    The ID is not a unique reference.

    However, in practice, you differentiate by using the parent view.

    If we consider that 'this' is an Activity, set up with a layout that contains your buttons, then:

    Button button = (Button) this.findViewById( R.id.id_name );
    

    will return the first one it finds in the layout (I think - not sure the actual behaviour is defined).

    However what you might do is call findViewById on some parent view that contains only one such instance with that ID.

    LinearLayout okParent = (LinearLayout) this.findViewById( R.id.okLayout );
    LinearLayout cancelParent = (LinearLayout) this.findViewById( R.id.cancelLayout );
    
    Button okButton = (Button) okParent.findViewById( R.id.id_name );
    Button cancelButton = (Button) cancelParent.findViewById( R.id.id_name );
    

    Conceptually, this is a sort of path based lookup. You should be careful to design your layouts such that this is possible.

提交回复
热议问题