Just wanted to ask a quick question. Here is an example XML tag. Which is the proper way to end it and what are the differences between both?
<TextView **code** />
<TextView> **code** </TextView>
CodePudding user response:
XML in general
Only attributes may appear
<TextView
here/>
or<TextView
here>
...</TextView>
— typically used for scalar values.Child elements may appear
<TextView>
here</TextView>
— typically used for values with substructure.
For empty elements, <TextView/>
and <TextView></TextView>
are equivalent.
Android Layout XML
Android XML uses both elements and attributes and generally follows the common guidance that elements be used when further substructure is required and attributes be used for scalar values. See the documentation for details.
See also
CodePudding user response:
Both are acceptable. The one you use depends on what you are doing. For example, a <LinearLayout>
tag will contain other tags nested inside, so you use the 2nd version. For example, if you include two TextView
s inside, it looks like this:
<LinearLayout>
<TextView />
<TextView />
</LinearLayout>
On the other hand, a <TextView>
never contains other tags inside it, but will have attributes:
<TextView
android:id="@ id/text_view_id"
android:layout_height="wrap_content"
android:layout_width="wrap_content"
android:text="@string/hello" />
As you work more with Android's XML layouts, you will start to see patterns and get the hang of which of these you will use in a given situation.