Proper way to end XML tags

Viewed 42

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?

  1. <TextView **code** />
  2. <TextView> **code** </TextView>
2 Answers

XML in general

  • Attributes may appear <TextView here /> or <TextView here >...</TextView>
    — typically used for scalar values.

  • Elements (or text) 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

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 TextViews 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.

Related