Базовая XML-разметка для UI в Android Studio

XML-разметка в Android Studio хранится в res/layout: используйте корневой контейнер (ConstraintLayout или LinearLayout), указывайте xmlns и стандартные android:layout_width/height; текст выносите в strings.xml — это обеспечит локализацию и чистоту кода.

Структура XML и корневые контейнеры

Каждый layout-файл начинается с корня и пространства имён:

<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    android:orientation="vertical"
    android:padding="16dp">
    <!-- элементы -->
</LinearLayout>

Ключевые атрибуты:

  • xmlns:android — обязательный namespace.
  • android:layout_width / android:layout_height — значения: wrap_content, match_parent или фиксированный (например, 100dp).
  • Используйте dp для размеров и отступов, sp — для текста.

Совет по выбору контейнера: для простых вертикальных списков — LinearLayout; для гибкой компоновки без глубокой вложенности — ConstraintLayout.

TextView и EditText: атрибуты и лучшие практики

TextView — для отображения текста; EditText — для ввода. Часто используемые атрибуты:

  • android:text / android:textSize (в sp) / android:textColor
  • android:gravity — выравнивание внутри view
  • android:hint — подсказка для EditText
  • android:inputType — textEmailAddress, number, textPassword и т. п.
  • android:maxLines, android:imeOptions — управление клавиатурой

Пример TextView:

<TextView
    android:layout_width="wrap_content"
    android:layout_height="wrap_content"
    android:text="@string/welcome_message"
    android:textSize="18sp"
    android:textStyle="bold"
    android:gravity="center"
    android:layout_marginBottom="16dp" />

Пример полей ввода (внутри ConstraintLayout используйте 0dp для ширины с привязками start/end):

<EditText
    android:id="@+id/email"
    android:layout_width="0dp"
    android:layout_height="wrap_content"
    android:inputType="textEmailAddress"
    android:hint="@string/email_hint"
    android:maxLines="1"
    android:imeOptions="actionNext"
    app:layout_constraintStart_toStartOf="parent"
    app:layout_constraintEnd_toEndOf="parent"
    app:layout_constraintTop_toBottomOf="@id/title"
    android:layout_marginTop="24dp" />

Всегда используйте sp для размера шрифта — это учитывает пользовательские настройки доступа.

Строки в res/values/strings.xml и локализация

Не хардкодьте текст в layout. Примеры в strings.xml:

<resources>
    <string name="app_name">MyApp</string>
    <string name="welcome_message">Добро пожаловать!</string>
    <string name="email_hint">Введите email</string>
    <string name="password_hint">Пароль</string>
</resources>

Форматирование через ресурсы:

  • В XML: android:text="@string/hello"
  • В коде: getString(R.string.hello, "User") для подстановки параметров.

Забытые строки (хардкод) усложняют локализацию и могут вызвать ошибки при проверке релиза. Запускайте Analyze > Inspect Code.

Простой экран: шаблон activity_main.xml

Минимальный пример с заголовком, двумя полями и кнопкой в ConstraintLayout:

<?xml version="1.0" encoding="utf-8"?>
<androidx.constraintlayout.widget.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"
    android:padding="24dp">

    <TextView
        android:id="@+id/title"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:text="@string/welcome_message"
        android:textSize="24sp"
        app:layout_constraintTop_toTopOf="parent"
        app:layout_constraintStart_toStartOf="parent"
        app:layout_constraintEnd_toEndOf="parent" />

    <EditText
        android:id="@+id/email"
        android:layout_width="0dp"
        android:layout_height="wrap_content"
        android:inputType="textEmailAddress"
        android:hint="@string/email_hint"
        app:layout_constraintTop_toBottomOf="@id/title"
        app:layout_constraintStart_toStartOf="parent"
        app:layout_constraintEnd_toEndOf="parent"
        android:layout_marginTop="24dp" />

    <EditText
        android:id="@+id/password"
        android:layout_width="0dp"
        android:layout_height="wrap_content"
        android:inputType="textPassword"
        android:hint="@string/password_hint"
        app:layout_constraintTop_toBottomOf="@id/email"
        app:layout_constraintStart_toStartOf="parent"
        app:layout_constraintEnd_toEndOf="parent"
        android:layout_marginTop="12dp" />

    <Button
        android:id="@+id/loginButton"
        android:layout_width="0dp"
        android:layout_height="wrap_content"
        android:text="@string/login"
        app:layout_constraintTop_toBottomOf="@id/password"
        app:layout_constraintStart_toStartOf="parent"
        app:layout_constraintEnd_toEndOf="parent"
        android:layout_marginTop="24dp" />
</androidx.constraintlayout.widget.ConstraintLayout>

Частые ошибки

  • Хардкод текста в layout вместо strings.xml.
  • Слишком глубокая вложенность (больше 3 уровней) — заменяйте на ConstraintLayout.
  • Использование px вместо dp/sp.
  • Отсутствие android:contentDescription у интерактивных изображений — ломает доступность.
  • Забытые ограничения в ConstraintLayout => неожиданный размер/позиция.

FAQ

  • Нужно ли всегда использовать ConstraintLayout? Нет — для простых вертикальных списков LinearLayout удобнее. Но для сложных макетов ConstraintLayout эффективнее.
  • Как выбрать между wrap_content и match_parent? wrap_content подгоняет размер под содержимое, match_parent занимает весь доступный размер родителя.
  • Почему текст выглядит слишком крупным/мелким на устройстве? Проверяйте sp и масштаб шрифта в системных настройках; тестируйте на разных DPI.

С этими практиками вы покроете большинство типовых экранов и избежите распространённых ошибок при верстке UI в Android Studio.