Я хотів би ввести деякі коментарі до файлів XML-макета, як би це зробити?
Я хотів би ввести деякі коментарі до файлів XML-макета, як би це зробити?
Відповіді:
Як було сказано, коментар у XML такий
<!-- this is a comment -->
Зауважте, що вони можуть охоплювати декілька ліній
<!--
This is a comment
on multiple lines
-->
Але вони не можуть бути вкладені
<!-- This <!-- is a comment --> This is not -->
Також ви не можете використовувати їх всередині тегів
<EditText <!--This is not valid--> android:layout_width="fill_parent" />
Всесвітній веб-консорціум (W3C) фактично визначив інтерфейс для коментарів. Визначення говоритьall the characters between the starting ' <!--' and ending '-->' form a part of comment content and no lexical check is done on the content of a comment .
Більш детальна інформація доступна на сайті developer.android.com сайті .
Таким чином, ви можете просто додати свій коментар між будь-яким початковим і кінцевим тегом. У IDE Eclipse просто наберіть текст<!-- автоматично завершить коментар для вас. Потім ви можете додати текст коментаря між ними.
Наприклад:
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:tools="http://schemas.android.com/tools"
android:layout_width="fill_parent"
android:layout_height="fill_parent"
android:orientation="vertical"
tools:context=".TicTacToe" >
<!-- This is a comment -->
</LinearLayout>
Мета конкретного згадування in between полягає в тому, що ви не можете використовувати його всередині тегу.
Наприклад:
<TextView
android:text="@string/game_title"
<!-- This is a comment -->
android:layout_height="wrap_content"
android:layout_width="fill_parent"/>
невірно і призведе до наступної помилки
Element type "TextView" must be followed by either attribute specifications, ">" or "/>".
ctrl + shift + / Ви можете коментувати код.
<!--
<View
android:layout_marginTop="@dimen/d10dp"
android:id="@+id/view1"
android:layout_below="@+id/tv_change_password"
android:layout_width="fill_parent"
android:layout_height="1dp"
android:background="#c0c0c0"/>-->
<!-- comment here -->
Можна створити спеціальні атрибути, які можна використовувати для цілей коментування / документації.
У наведеному нижче прикладі documentation:infoвизначається атрибут із прикладом значення коментаря:
<RelativeLayout
xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:documentation="documentation.mycompany.com"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:id="@+id/relLayoutID"
documentation:info="This is an example comment" >
<TextView
documentation:purpose="Instructions label"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="Click here to begin."
android:id="@+id/tvMyLabel"
android:layout_alignParentTop="true"
android:layout_alignParentStart="true"
documentation:info="Another example comment"
documentation:translation_notes="This control should use the fewest characters possible, as space is limited"
/>
</RelativeLayout>
Зауважте, що в цьому випадку documentation.mycompany.comце лише визначення нового користувальницького простору імен XML (of documentation), і, таким чином, є лише унікальною рядком URI - це може бути будь-що, поки це унікально. documentationПраворуч від xmlns:також може бути що завгодно - це працює точно так само , що чимandroid: XML - простір імен визначається і використовується.
Використовуючи цей формат, будь-яка кількість атрибутів може бути створена, наприклад documentation:info, documentation:translation_notesтощо, поряд із значенням опису, формат якого такий же, як і будь-який атрибут XML.
Підсумовуючи:
xmls:my_new_namespaceатрибут до кореневого (верхнього рівня) елемента XML у файлі макета XML. Встановіть його значення на унікальну рядок<TextView my_new_namespace:my_new_doc_property="description" />tools:замість цього спеціальний простір імен, який відкидається. (Ймовірно, його не було, коли ця відповідь була опублікована, але ця сторінка продовжує отримувати нових глядачів.)
Якщо ви хочете прокоментувати, Android Studioпросто натисніть:
Ctrl+ /у Windows / Linux
Cmd+ /на Mac.
Це працює в таких файлах XML, strings.xmlяк і в файлах коду, як MainActivity.java.
Ви також можете додати коментар, натиснувши Ctrl + shift + / та shift + / для одного рядка.
Неймовірно, що в 2019 році за допомогою студії Android 3.3 (не знаю точної версії, принаймні 3.3) можна використовувати коментар з подвійною косою рисою до xml.
Але якщо ви використовуєте коментар з подвійною косою рисою в xml, IDE показує попередження.
<?xml version="1.0" encoding="utf-8"?>
<android.support.constraint.ConstraintLayout
xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:app="http://schemas.android.com/apk/res-auto"
android:layout_width="match_parent"
android:layout_height="match_parent">
// this works
/* this works too */
/*
multi line comment
multi line comment
*/
<TextView
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="Hello World! yeah"
app:layout_constraintBottom_toBottomOf="parent"
app:layout_constraintLeft_toLeftOf="parent"
app:layout_constraintRight_toRightOf="parent"
app:layout_constraintTop_toTopOf="parent" />
</android.support.constraint.ConstraintLayout>
Unexpected text found in layout file: ....
З примітки Федеріко Куллоки:
Також ви не можете використовувати їх всередині тегів
Засоби; ви повинні розмістити коментар у верхній або нижній частині файлу - усі місця, які ви дійсно хочете додати коментарі, принаймні знаходяться всередині тегу макета верхнього рівня.