how does multiple component with same id work in android?

后端 未结 3 887
再見小時候
再見小時候 2021-01-23 04:59

I have defined several layouts, where few id\'s are multiple defined. I am confused how does it work? why doesn\'t it give error just like we get in java code? and most importan

3条回答
  •  执笔经年
    2021-01-23 05:57

    You can findViewById of the current view hierarchy set to the activity. You cannot have same id for the view's in the same view tree. (must be unique).

    Quoting from the docs

    Any View object may have an integer ID associated with it, to uniquely identify the View within the tree. When the application is compiled, this ID is referenced as an integer, but the ID is typically assigned in the layout XML file as a string, in the id attribute. This is an XML attribute common to all View objects (defined by the View class) and you will use it very often.

    http://developer.android.com/guide/topics/ui/declaring-layout.html

    Example

    @Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);
        Button myButton = (Button) findViewById(R.id.my_button);
     }
    

    Xml

      

    Here

      Button myButton = (Button) findViewById(R.id.my_button);
    

    findViewById is the method R.id.button is an int value. Will have an entry in R.java which is auto generated. Here under the same xml file under the current view tree you cannot have views with same id.

    Open your R.java do not modify its content. R.java will look something like below

      public static final class id {
          public static final int my_button=0x7f080004; // this is the int value which is unique
       }
    

    In onCreate you refer like R.id.my_button.

    You can have ids same in different xml files because whenever you use findViewById() to get a reference to a part of your layout, the method only looks for that view in the currently inflated layout. (current view tree/hierarchy).

    But it is better have ids unique to avoid confusion.

提交回复
热议问题