Logic of xml-gui-attributes

Question:

It would seem that there is nothing complicated in writing a GUI using XML . We look in the Reference for classes inherited from View, write them in a hierarchical order, and initialize the necessary properties, which are again written in the documentation of each class.

But, for example, the android:layout_weight property is not a parameter of the TextView , but is added there if its ancestor is a TextView .

  <LinearLayout
      <TextView
          android:layout_weight="1"/>
  </LinearLayout>

My question is: what is the principle of such inheritance, how to distinguish inherited parameters from non-inherited ones, and are there any other non-obvious points in writing a GUI using XML ?

Answer:

When adding a view somewhere in the code, you use layout-specific LayoutParams :

// грубо
relativeLayout.addView(myView, new RelativeLayout.LayoutParams(...));

Those. in addition to the parameters of the view itself, you also need to use the parameters of the layout of the container in which you add it. (in case of one-argument addView(View view) default parameters are used)

The xml parser will do the same when generating bytecode: if the view is in a RelativeLayout , its tag may contain attributes for RelativeLayout.LayoutParams . If you specify them there, it will create LayoutParams with your attributes, if not, it will use the default ones.

So:

  • There is no inheritance, just the logic of describing layouts in xml and in the code is slightly different.
  • All LayoutParams any ViewGroup ( LinearLayout , RelativeLayout ) in xml can be added to the child tag.
  • There is no ironclad way to distinguish child parameters from parent layout parameters "on the fly". But there is also no need. Parameters are documented ( LinearLayout.LayoutParams ) By choosing a layout, you solve some problem, which means that you know what layout parameters you want to use, you are unlikely to confuse them with view parameters.
  • After a couple of months of working with layouts, you will know them by heart 🙂
Scroll to Top