MDC-103 Android: темы материалов с цветом, движением и типом (Java)

logo_components_color_2x_web_96dp.png

Компоненты материалов (MDC) помогают разработчикам реализовать Material Design. Созданный командой инженеров и дизайнеров UX в Google, MDC включает в себя десятки красивых и функциональных компонентов пользовательского интерфейса и доступен для Android, iOS, Интернета и Flutter.

material.io/разработка

В лабораториях кода MDC-101 и MDC-102 вы использовали Material Components (MDC) для создания основ приложения Shrine , приложения для электронной коммерции, которое продает одежду и товары для дома. Это приложение содержит поток пользователя, который начинается с экрана входа и переносит пользователя на главный экран, на котором отображаются продукты.

Недавнее расширение Material Design дает дизайнерам и разработчикам больше гибкости для выражения бренда своего продукта. Теперь вы можете использовать MDC, чтобы настроить Shrine и отразить его уникальный стиль больше, чем когда-либо.

Что вы будете строить

В этой кодовой лаборатории вы настроите Shrine, чтобы он отражал его бренд, используя:

  • Цвет
  • Типография
  • Высота
  • Макет

Компоненты и подсистемы MDC Android, используемые в этой кодовой лаборатории

  • Темы
  • Типография
  • Высота

Что вам понадобится

  • Базовые знания Android-разработки
  • Android Studio (скачайте здесь , если у вас ее еще нет)
  • Эмулятор или устройство Android (доступно через Android Studio)
  • Пример кода (см. следующий шаг)

Как бы вы оценили свой уровень опыта создания приложений для Android?

Новичок Средний Опытный

Продолжая с MDC-102?

Если вы выполнили MDC-102, ваш код должен быть готов к работе в этой лаборатории кода. Перейдите к шагу 3: Измените цвет .

Загрузите начальное приложение Codelab

Скачать стартовое приложение

Стартовое приложение находится в material-components-android-codelabs-103-starter/java . Обязательно cd в этот каталог перед началом.

...или клонируйте его с GitHub

Чтобы клонировать эту лабораторию кода из GitHub, выполните следующие команды:

git clone https://github.com/material-components/material-components-android-codelabs
cd material-components-android-codelabs/
git checkout 103-starter

Загрузите стартовый код в Android Studio

  1. После завершения работы мастера установки и отображения окна « Добро пожаловать в Android Studio » нажмите «Открыть существующий проект Android Studio» . Перейдите в каталог, в который вы установили пример кода, и выберите java -> shrine (или выполните поиск shrine на своем компьютере), чтобы открыть проект Shrine.
  2. Подождите, пока Android Studio создаст и синхронизирует проект, о чем свидетельствуют индикаторы активности в нижней части окна Android Studio.
  3. На этом этапе Android Studio может вызвать некоторые ошибки сборки из-за отсутствия Android SDK или инструментов сборки, таких как показанный ниже. Следуйте инструкциям в Android Studio, чтобы установить/обновить их и синхронизировать свой проект.

Добавить зависимости проекта

Проекту нужна зависимость от библиотеки поддержки MDC Android . В загруженном образце кода эта зависимость уже должна быть указана, но рекомендуется выполнить следующие шаги, чтобы убедиться в этом.

  1. Перейдите к файлу build.gradle модуля app и убедитесь, что блок dependencies включает зависимость от MDC Android:
api 'com.google.android.material:material:1.1.0-alpha06'
  1. (Необязательно) При необходимости отредактируйте файл build.gradle , чтобы добавить следующие зависимости и синхронизировать проект.
dependencies {
    api 'com.google.android.material:material:1.1.0-alpha06'
    implementation 'androidx.legacy:legacy-support-v4:1.0.0'
    implementation 'com.android.volley:volley:1.1.1'
    implementation 'com.google.code.gson:gson:2.8.5'
    implementation "org.jetbrains.kotlin:kotlin-stdlib-jdk7:1.3.21"
    testImplementation 'junit:junit:4.12'
    androidTestImplementation 'androidx.test:core:1.1.0'
    androidTestImplementation 'androidx.test.ext:junit:1.1.0'
    androidTestImplementation 'androidx.test:runner:1.2.0-alpha05'
    androidTestImplementation 'androidx.test.espresso:espresso-core:3.2.0-alpha05'
}

Запустите стартовое приложение

  1. Убедитесь, что конфигурация сборки слева от кнопки «Выполнить/Воспроизвести»app .
  2. Нажмите зеленую кнопку Run/Play, чтобы создать и запустить приложение.
  3. В окне Select Deployment Target , если у вас уже есть устройство Android, указанное в списке доступных устройств, перейдите к шагу 8 . В противном случае нажмите «Создать новое виртуальное устройство» .
  4. На экране « Выбор оборудования » выберите телефонное устройство, например Pixel 2 , и нажмите « Далее ».
  5. На экране System Image выберите последнюю версию Android , желательно самый высокий уровень API. Если он не установлен, щелкните показанную ссылку « Загрузить » и завершите загрузку.
  6. Нажмите «Далее» .
  7. На экране виртуального устройства Android (AVD) оставьте настройки без изменений и нажмите « Готово ».
  8. Выберите устройство Android в диалоговом окне цели развертывания.
  9. Нажмите «ОК» .
  10. Android Studio создает приложение, развертывает его и автоматически открывает на целевом устройстве.

Успех! Вы должны увидеть страницу входа в Shrine на вашем устройстве или в эмуляторе. Когда вы нажмете «Далее», появится домашняя страница Shrine с панелью приложений вверху и сеткой изображений продуктов внизу.

Давайте сделаем так, чтобы верхняя панель приложения соответствовала бренду Shrine, изменив ее цвет, высоту и типографику.

Эта цветовая тема была создана дизайнером с использованием пользовательских цветов (показанных на изображении ниже). Он содержит цвета, выбранные из бренда Shrine и примененные к редактору тем материалов, который расширил их для создания более полной палитры. (Эти цвета не из цветовых палитр Material 2014 года.)

Редактор тем материалов организовал их в оттенки с числовыми метками, включая метки от 50, 100, 200, .... до 900 каждого цвета. Shrine использует только оттенки 50, 100 и 300 из розового образца и 900 из коричневого образца.

Давайте изменим цвет верхней панели приложения, чтобы отразить эту цветовую схему.

Установите colorPrimaryDark и colorAccent

В colors.xml измените следующие строки. Помимо прочего, атрибут colorAccent управляет цветом верхней панели приложения, а атрибут colorPrimaryDark управляет цветом строки состояния.

цвета.xml

<color name="colorPrimaryDark">#FBB8AC</color>
<color name="colorAccent">#FEDBD0</color>

Чтобы использовать темные значки в строке состояния, добавьте следующее в Theme.Shrine , тему приложения Shrine:

стили.xml

<item name="android:windowLightStatusBar" tools:targetApi="m">true</item>

Ваши colors.xml и styles.xml должны выглядеть следующим образом:

цвета.xml

<?xml version="1.0" encoding="utf-8"?>
<resources>
   <color name="colorPrimary">#E0E0E0</color>
   <color name="colorPrimaryDark">#FBB8AC</color>
   <color name="colorAccent">#FEDBD0</color>
   <color name="toolbarIconColor">#FFFFFF</color>
   <color name="loginPageBackgroundColor">#FFFFFF</color>
   <color name="productGridBackgroundColor">#FFFFFF</color>
</resources>

стили.xml

<resources xmlns:android="http://schemas.android.com/tools">

   <!-- Base application theme. -->
   <style name="Theme.Shrine" parent="Theme.MaterialComponents.Light.NoActionBar">
       <!-- Customize your theme here. -->
       <item name="colorPrimary">@color/colorPrimary</item>
       <item name="colorPrimaryDark">@color/colorPrimaryDark</item>
       <item name="colorAccent">@color/colorAccent</item>
       <item name="android:windowLightStatusBar" tools:targetApi="m">true</item>
   </style>

   <style name="Widget.Shrine.Toolbar" parent="Widget.AppCompat.Toolbar">
       <item name="android:background">?attr/colorAccent</item>
       <item name="android:theme">@style/ThemeOverlay.AppCompat.Dark.ActionBar</item>
       <item name="popupTheme">@style/ThemeOverlay.AppCompat.Light</item>
   </style>

</resources>

В colors.xml добавьте новый цветовой ресурс textColorPrimary со значением #442C2E и обновите атрибут toolbarIconColor , чтобы он ссылался на цвет textColorPrimary .

Обновите файл styles.xml , чтобы задать для атрибута android:textColorPrimary textColorPrimary цвет textColorPrimary.

Установка android:textColorPrimary в Theme.Shrine текст во всех элементах, включая верхнюю панель приложения и значки на нашей верхней панели приложения.

И еще: установите для атрибута android:theme в стиле Widget.Shrine.Toolbar значение Theme.Shrine .

Ваши colors.xml и styles.xml должны выглядеть следующим образом:

цвета.xml

<?xml version="1.0" encoding="utf-8"?>
<resources>
   <color name="colorPrimary">#E0E0E0</color>
   <color name="colorPrimaryDark">#FBB8AC</color>
   <color name="colorAccent">#FEDBD0</color>
   <color name="textColorPrimary">#442C2E</color>
   <color name="toolbarIconColor">@color/textColorPrimary</color>
   <color name="loginPageBackgroundColor">#FFFFFF</color>
   <color name="productGridBackgroundColor">#FFFFFF</color>
</resources>

стили.xml

<resources xmlns:android="http://schemas.android.com/tools">

   <!-- Base application theme. -->
   <style name="Theme.Shrine" parent="Theme.MaterialComponents.Light.NoActionBar">
       <!-- Customize your theme here. -->
       <item name="colorPrimary">@color/colorPrimary</item>
       <item name="colorPrimaryDark">@color/colorPrimaryDark</item>
       <item name="colorAccent">@color/colorAccent</item>
       <item name="android:windowLightStatusBar" tools:targetApi="m">true</item>
       <item name="android:textColorPrimary">@color/textColorPrimary</item>
   </style>

   <style name="Widget.Shrine.Toolbar" parent="Widget.AppCompat.Toolbar">
       <item name="android:background">?attr/colorAccent</item>
       <item name="android:theme">@style/Theme.Shrine</item>
       <item name="popupTheme">@style/ThemeOverlay.AppCompat.Light</item>
   </style>

</resources>

Стройте и запускайте. Теперь ваша сетка продуктов должна выглядеть так:

Давайте изменим стиль экрана входа в систему, чтобы он соответствовал нашей цветовой схеме.

Стиль текстовых полей

Давайте изменим текстовые поля на странице входа, чтобы они были обведены контуром, и используем лучшие цвета для нашего макета.

Добавьте в файл colors.xml следующий цветовой ресурс:

цвета.xml

<color name="textInputOutlineColor">#FBB8AC</color>

Добавьте два новых стиля в файл styles.xml :

стили.xml

<style name="Widget.Shrine.TextInputLayout" parent="Widget.MaterialComponents.TextInputLayout.OutlinedBox">
   <item name="hintTextAppearance">@style/TextAppearance.Shrine.TextInputLayout.HintText</item>
   <item name="hintTextColor">@color/textColorPrimary</item>
   <item name="android:paddingBottom">8dp</item>
   <item name="boxStrokeColor">@color/textInputOutlineColor</item>
</style>

<style name="TextAppearance.Shrine.TextInputLayout.HintText" parent="TextAppearance.MaterialComponents.Subtitle2">
   <item name="android:textColor">?android:attr/textColorPrimary</item>
</style>

Наконец, установите новый стиль для атрибута стиля обоих XML-компонентов TextInputLayout в shr_login_fragment.xml :

shr_login_fragment.xml

<com.google.android.material.textfield.TextInputLayout
   style="@style/Widget.Shrine.TextInputLayout"
   android:layout_width="match_parent"
   android:layout_height="wrap_content"
   android:hint="@string/shr_hint_username">

   <com.google.android.material.textfield.TextInputEditText
       android:layout_width="match_parent"
       android:layout_height="wrap_content"
       android:inputType="text"
       android:maxLines="1" />
</com.google.android.material.textfield.TextInputLayout>

<com.google.android.material.textfield.TextInputLayout
   android:id="@+id/password_text_input"
   style="@style/Widget.Shrine.TextInputLayout"
   android:layout_width="match_parent"
   android:layout_height="wrap_content"
   android:hint="@string/shr_hint_password"
   app:errorEnabled="true">

   <com.google.android.material.textfield.TextInputEditText
       android:id="@+id/password_edit_text"
       android:layout_width="match_parent"
       android:layout_height="wrap_content"
       android:inputType="textPassword" />
</com.google.android.material.textfield.TextInputLayout>

Стиль цветов кнопок

Наконец, настройте цвета кнопок на странице входа. Добавьте следующие стили в файл styles.xml :

стили.xml

<style name="Widget.Shrine.Button" parent="Widget.MaterialComponents.Button">
   <item name="android:textColor">?android:attr/textColorPrimary</item>
   <item name="backgroundTint">?attr/colorPrimaryDark</item>
</style>

<style name="Widget.Shrine.Button.TextButton" parent="Widget.MaterialComponents.Button.TextButton">
   <item name="android:textColor">?android:attr/textColorPrimary</item>
</style>

Стиль Widget.Shrine.Button расширяет стиль MaterialButton по умолчанию и изменяет цвет текста и оттенок фона кнопки. Widget.Shrine.Button.TextButton стандартного текстового стиля MaterialButton и изменяет только цвет текста.

Установите стиль Widget.Shrine.Button для кнопки «Далее» и стиль Widget.Shrine.Button.TextButton для кнопки «Отмена» следующим образом:

shr_login_fragment.xml

<RelativeLayout
   android:layout_width="match_parent"
   android:layout_height="wrap_content">

   <com.google.android.material.button.MaterialButton
       android:id="@+id/next_button"
       style="@style/Widget.Shrine.Button"
       android:layout_width="wrap_content"
       android:layout_height="wrap_content"
       android:layout_alignParentEnd="true"
       android:layout_alignParentRight="true"
       android:text="@string/shr_button_next" />

   <com.google.android.material.button.MaterialButton
       android:id="@+id/cancel_button"
       style="@style/Widget.Shrine.Button.TextButton"
       android:layout_width="wrap_content"
       android:layout_height="wrap_content"
       android:layout_marginEnd="12dp"
       android:layout_marginRight="12dp"
       android:layout_toStartOf="@id/next_button"
       android:layout_toLeftOf="@id/next_button"
       android:text="@string/shr_button_cancel" />

</RelativeLayout>

Обновите цвет логотипа Shrine на странице входа. Для этого потребуется небольшое изменение векторного рисунка, shr_logo.xml . Откройте файл drawable и измените свойство android:fillAlpha на 1. Drawable должен выглядеть следующим образом:

shr_logo.xml

<vector xmlns:android="http://schemas.android.com/apk/res/android"
   android:width="149dp"
   android:height="152dp"
   android:tint="?attr/colorControlNormal"
   android:viewportWidth="149"
   android:viewportHeight="152">
   <path
       android:fillAlpha="1"
       android:fillColor="#DADCE0"
       android:fillType="evenOdd"
       android:pathData="M42.262,0L0,38.653L74.489,151.994L148.977,38.653L106.723,0M46.568,11.11L21.554,33.998L99.007,33.998L99.007,11.11L46.568,11.11ZM110.125,18.174L110.125,33.998L127.416,33.998L110.125,18.174ZM80.048,45.116L80.048,123.296L131.426,45.116L80.048,45.116ZM17.551,45.116L33.976,70.101L68.93,70.101L68.93,45.116L17.551,45.116ZM41.284,81.219L68.93,123.296L68.93,81.219L41.284,81.219Z"
       android:strokeWidth="1"
       android:strokeAlpha="0.4"
       android:strokeColor="#00000000" />
</vector>

Установите для атрибута android:tint логотипа <ImageView> в shr_login_fragment.xml значение ?android:attr/textColorPrimary следующим образом:

shr_login_fragment.xml

<ImageView
   android:layout_width="64dp"
   android:layout_height="64dp"
   android:layout_gravity="center_horizontal"
   android:layout_marginTop="48dp"
   android:layout_marginBottom="16dp"
   android:tint="?android:attr/textColorPrimary"
   app:srcCompat="@drawable/shr_logo" />

Стройте и запускайте. Теперь ваш экран входа в систему должен выглядеть так:

В дополнение к изменению цвета ваш дизайнер также дал вам определенную типографику для использования на сайте. Давайте добавим это и на верхнюю панель приложений.

Стиль верхней панели приложений

Настройте внешний вид текста верхней панели приложений в соответствии со спецификацией, предоставленной вашим дизайнером. Добавьте следующий стиль оформления текста в styles.xml и задайте для свойства titleTextAppearance ссылку на этот стиль в стиле Widget.Shrine.Toolbar .

стили.xml

<style name="Widget.Shrine.Toolbar" parent="Widget.AppCompat.Toolbar">
   <item name="android:background">?attr/colorAccent</item>
   <item name="android:theme">@style/Theme.Shrine</item>
   <item name="popupTheme">@style/ThemeOverlay.AppCompat.Light</item>
   <item name="titleTextAppearance">@style/TextAppearance.Shrine.Toolbar</item>
</style>

<style name="TextAppearance.Shrine.Toolbar" parent="TextAppearance.MaterialComponents.Button">
   <item name="android:textSize">16sp</item>
</style>

Ваши colors.xml и styles.xml должны выглядеть следующим образом:

цвета.xml

<?xml version="1.0" encoding="utf-8"?>
<resources>
   <color name="colorPrimary">#E0E0E0</color>
   <color name="colorPrimaryDark">#FBB8AC</color>
   <color name="colorAccent">#FEDBD0</color>
   <color name="textColorPrimary">#442C2E</color>
   <color name="toolbarIconColor">@color/textColorPrimary</color>
   <color name="loginPageBackgroundColor">#FFFFFF</color>
   <color name="productGridBackgroundColor">#FFFFFF</color>
   <color name="textInputOutlineColor">#FBB8AC</color>
</resources>

стили.xml

<resources xmlns:android="http://schemas.android.com/tools">

   <!-- Base application theme. -->
   <style name="Theme.Shrine" parent="Theme.MaterialComponents.Light.NoActionBar">
       <!-- Customize your theme here. -->
       <item name="colorPrimary">@color/colorPrimary</item>
       <item name="colorPrimaryDark">@color/colorPrimaryDark</item>
       <item name="colorAccent">@color/colorAccent</item>
       <item name="android:windowLightStatusBar" tools:targetApi="m">true</item>
       <item name="android:textColorPrimary">@color/textColorPrimary</item>
   </style>

   <style name="Widget.Shrine.TextInputLayout" parent="Widget.MaterialComponents.TextInputLayout.OutlinedBox">
       <item name="hintTextAppearance">@style/TextAppearance.Shrine.TextInputLayout.HintText</item>
       <item name="hintTextColor">@color/textColorPrimary</item>
       <item name="android:paddingBottom">8dp</item>
       <item name="boxStrokeColor">@color/textInputOutlineColor</item>
   </style>

   <style name="TextAppearance.Shrine.TextInputLayout.HintText" parent="TextAppearance.MaterialComponents.Subtitle2">
       <item name="android:textColor">?android:attr/textColorPrimary</item>
   </style>


   <style name="Widget.Shrine.Button" parent="Widget.MaterialComponents.Button">
       <item name="android:textColor">?android:attr/textColorPrimary</item>
       <item name="backgroundTint">?attr/colorPrimaryDark</item>
   </style>

   <style name="Widget.Shrine.Button.TextButton" parent="Widget.MaterialComponents.Button.TextButton">
       <item name="android:textColor">?android:attr/textColorPrimary</item>
   </style>

   <style name="Widget.Shrine.Toolbar" parent="Widget.AppCompat.Toolbar">
       <item name="android:background">?attr/colorAccent</item>
       <item name="android:theme">@style/Theme.Shrine</item>
       <item name="popupTheme">@style/ThemeOverlay.AppCompat.Light</item>
       <item name="titleTextAppearance">@style/TextAppearance.Shrine.Toolbar</item>
   </style>

   <style name="TextAppearance.Shrine.Toolbar" parent="TextAppearance.MaterialComponents.Button">
       <item name="android:textSize">16sp</item>
   </style>

</resources>

Стиль этикеток

Мы изменим стиль этикеток карточек продуктов, чтобы использовать правильный вид текста и расположить их по центру по горизонтали внутри карточки.

Обновите типографику на метке заголовка с textAppearanceHeadline6 на textAppearanceSubtitle2 следующим образом:

shr_product_card.xml

<TextView
   android:id="@+id/product_title"
   android:layout_width="match_parent"
   android:layout_height="wrap_content"
   android:text="@string/shr_product_title"
   android:textAppearance="?attr/textAppearanceSubtitle2" />

Чтобы центрировать метки изображений, измените метку <TextView> в shr_product_card.xml , чтобы установить атрибут android:textAlignment="center" :

shr_product_card.xml

<LinearLayout
   android:layout_width="match_parent"
   android:layout_height="wrap_content"
   android:orientation="vertical"
   android:padding="16dp">

   <TextView
       android:id="@+id/product_title"
       android:layout_width="match_parent"
       android:layout_height="wrap_content"
       android:text="@string/shr_product_title"
       android:textAlignment="center"
       android:textAppearance="?attr/textAppearanceSubtitle2" />

   <TextView
       android:id="@+id/product_price"
       android:layout_width="match_parent"
       android:layout_height="wrap_content"
       android:text="@string/shr_product_description"
       android:textAlignment="center"
       android:textAppearance="?attr/textAppearanceBody2" />
</LinearLayout>

Стройте и запускайте. Теперь экран сетки вашего продукта должен выглядеть так:

Давайте изменим типографику экрана входа в систему, чтобы она соответствовала.

Изменить шрифт экрана входа в систему

В styles.xml добавьте следующий стиль:

стили.xml

<style name="TextAppearance.Shrine.Title" parent="TextAppearance.MaterialComponents.Headline4">
   <item name="textAllCaps">true</item>
   <item name="android:textStyle">bold</item>
   <item name="android:textColor">?android:attr/textColorPrimary</item>
</style>

В shr_login_fragment.xml установите новый стиль для вашего заголовка «SHRINE» <TextView> (и удалите textAllCaps и textSize , которые там есть):

shr_login_fragment.xml

<TextView
   android:layout_width="wrap_content"
   android:layout_height="wrap_content"
   android:layout_gravity="center_horizontal"
   android:layout_marginBottom="132dp"
   android:text="@string/shr_app_name"
   android:textAppearance="@style/TextAppearance.Shrine.Title" />

Стройте и запускайте. Теперь ваш экран входа в систему должен выглядеть так:

Теперь, когда вы определили стиль страницы с определенным цветом и типографикой, которые соответствуют Shrine, давайте взглянем на карточки, на которых показаны продукты Shrine. Сейчас они размещены на белой поверхности под навигацией приложения. Давайте уделим продуктам больше внимания, чтобы привлечь к ним внимание.

Изменить высоту сетки продукта

Давайте изменим высоту верхней панели приложения и содержимого, чтобы оно выглядело так, как будто содержимое находится на листе, плавающем над верхней панелью приложения. Добавьте атрибут app:elevation в AppBarLayout и атрибут android:elevation в XML-компоненты shr_product_grid_fragment.xml NestedScrollView образом:

shr_product_grid_fragment.xml

<com.google.android.material.appbar.AppBarLayout
   android:layout_width="match_parent"
   android:layout_height="wrap_content"
   app:elevation="0dp">

   <androidx.appcompat.widget.Toolbar
       android:id="@+id/app_bar"
       style="@style/Widget.Shrine.Toolbar"
       android:layout_width="match_parent"
       android:layout_height="?attr/actionBarSize"
       app:navigationIcon="@drawable/shr_menu"
       app:title="@string/shr_app_name" />
</com.google.android.material.appbar.AppBarLayout>

<androidx.core.widget.NestedScrollView
   android:layout_width="match_parent"
   android:layout_height="match_parent"
   android:layout_marginTop="56dp"
   android:background="@color/productGridBackgroundColor"
   android:elevation="8dp"
   android:paddingStart="@dimen/shr_product_grid_spacing"
   android:paddingEnd="@dimen/shr_product_grid_spacing"
   app:layout_behavior="@string/appbar_scrolling_view_behavior">

   <androidx.appcompat.app.AlertController.RecycleListView
       android:id="@+id/recycler_view"
       android:layout_width="match_parent"
       android:layout_height="match_parent" />

</androidx.core.widget.NestedScrollView>

Изменить высоту карты (и цвет)

Вы можете настроить высоту каждой карточки, изменив app:cardElevation в shr_product_card.xml с 2dp на 0dp . Также измените app:cardBackgroundColor на @android:color/transparent .

shr_product_card.xml

<com.google.material.card.MaterialCardView 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="wrap_content"
   app:cardBackgroundColor="@android:color/transparent"
   app:cardElevation="0dp"
   app:cardPreventCornerOverlap="true">

Взглянем! Вы изменили высоту каждой карточки на странице сетки товаров.

Изменение высоты кнопки «Далее»

В styles.xml добавьте следующее свойство к стилю Widget.Shrine.Button :

стили.xml

<item name="android:stateListAnimator" tools:ignore="NewApi">
    @animator/shr_next_button_state_list_anim
</item>

Установка android:stateListAnimator в стиле Button позволяет кнопке Next использовать предоставленный нами аниматор.

Стройте и запускайте. Теперь ваш экран входа в систему должен выглядеть так:


Измените макет, чтобы отображать карточки с разным соотношением сторон и размером, чтобы каждая карточка отличалась от других.

Используйте поэтапный адаптер RecyclerView

Мы предоставили новый адаптер RecyclerView в пакете staggeredgridlayout , который отображает асимметричный макет карты в шахматном порядке, предназначенный для горизонтальной прокрутки. Не стесняйтесь копаться в этом коде самостоятельно, но мы не будем здесь останавливаться на том, как он реализован.

Чтобы использовать этот новый адаптер, измените метод onCreateView() в ProductGridFragment.java . Замените блок кода после комментария «настроить RecyclerView » следующим:

ProductGridFragment.java

// Set up the RecyclerView
RecyclerView recyclerView = view.findViewById(R.id.recycler_view);
recyclerView.setHasFixedSize(true);
GridLayoutManager gridLayoutManager = new GridLayoutManager(getContext(), 2, GridLayoutManager.HORIZONTAL, false);
gridLayoutManager.setSpanSizeLookup(new GridLayoutManager.SpanSizeLookup() {
   @Override
   public int getSpanSize(int position) {
       return position % 3 == 2 ? 2 : 1;
   }
});
recyclerView.setLayoutManager(gridLayoutManager);
StaggeredProductCardRecyclerViewAdapter adapter = new StaggeredProductCardRecyclerViewAdapter(
       ProductEntry.initProductEntryList(getResources()));
recyclerView.setAdapter(adapter);
int largePadding = getResources().getDimensionPixelSize(R.dimen.shr_staggered_product_grid_spacing_large);
int smallPadding = getResources().getDimensionPixelSize(R.dimen.shr_staggered_product_grid_spacing_small);
recyclerView.addItemDecoration(new ProductGridItemDecoration(largePadding, smallPadding));

Нам также потребуется внести небольшое изменение в наш product_grid_fragment.xml , чтобы удалить отступы из нашего NestedScrollView следующим образом:

shr_product_grid_fragment.xml

<androidx.core.widget.NestedScrollView
   android:layout_width="match_parent"
   android:layout_height="match_parent"
   android:layout_marginTop="56dp"
   android:background="@color/productGridBackgroundColor"
   app:layout_behavior="@string/appbar_scrolling_view_behavior"
   android:elevation="6dp">

Наконец, мы также настроим заполнение нашей карточки в RecyclerView , изменив ProductGridItemDecoration.java . Измените метод getItemOffsets() в ProductGridItemDecoration.java следующим образом:

ProductGridItemDecoration.java

@Override
public void getItemOffsets(Rect outRect, View view,
                          RecyclerView parent, RecyclerView.State state) {
   outRect.left = smallPadding;
   outRect.right = largePadding;
}

Стройте и запускайте. Элементы сетки продуктов теперь должны располагаться в шахматном порядке:

Цвет — это мощный способ выразить свой бренд, и небольшое изменение цвета может оказать большое влияние на ваш пользовательский опыт. Чтобы проверить это, давайте посмотрим, как выглядел бы Shrine, если бы цветовая схема бренда была совершенно другой.

Изменение стилей и цветов

В styles.xml добавьте следующую новую тему:

стили.xml

<style name="Theme.Shrine.Autumn" parent="Theme.Shrine">
   <item name="colorPrimary">#FFCF44</item>
   <item name="colorPrimaryDark">#FD9725</item>
   <item name="colorAccent">#FD9725</item>
   <item name="colorOnPrimary">#FFFFFF</item>
   <item name="colorError">#FD9725</item>
</style>

И в AndroidManifest.xml используйте эту новую тему в своем приложении:

AndroidManifest.xml

<application
   android:allowBackup="true"
   android:icon="@mipmap/ic_launcher"
   android:label="@string/shr_app_name"
   android:roundIcon="@mipmap/ic_launcher_round"
   android:supportsRtl="true"
   android:name="com.google.codelabs.mdc.java.shrine.application.ShrineApplication"
   android:theme="@style/Theme.Shrine.Autumn">
   <activity android:name=".MainActivity">
       <intent-filter>
           <action android:name="android.intent.action.MAIN" />

           <category android:name="android.intent.category.LAUNCHER" />
       </intent-filter>
   </activity>
</application>

Измените цвет значка панели инструментов в colors.xml , как показано ниже:

цвета.xml

<color name="toolbarIconColor">#FFFFFF</color>

Затем установите атрибут android:theme нашего стиля панели инструментов, чтобы ссылаться на текущую тему, используя атрибут «?theme», а не жестко кодируя его:

стили.xml

<style name="Widget.Shrine.Toolbar" parent="Widget.AppCompat.Toolbar">
   <item name="android:background">?attr/colorAccent</item>
   <item name="android:theme">?theme</item>
   <item name="popupTheme">@style/ThemeOverlay.AppCompat.Light</item>
   <item name="titleTextAppearance">@style/TextAppearance.Shrine.Toolbar</item>
</style>

Затем осветлите цвет текста подсказки в текстовых полях экрана входа в систему. Добавьте атрибут android:textColorHint в стиль текстовых полей:

стили.xml

<style name="Widget.Shrine.TextInputLayout" parent="Widget.MaterialComponents.TextInputLayout.OutlinedBox">
   <item name="hintTextAppearance">
@style/TextAppearance.Shrine.TextInputLayout.HintText
</item>
   <item name="android:paddingBottom">8dp</item>
   <item name="android:textColorHint">?attr/colorPrimaryDark</item>
</style>

Стройте и запускайте. Новая тема должна появиться для предварительного просмотра.

Отмените код, измененный в этом разделе, прежде чем переходить к MDC-104.

К настоящему моменту вы создали приложение, которое соответствует спецификациям дизайна от вашего дизайнера.

Следующие шаги

Вы использовали эти компоненты MDC: тему, типографику и высоту. Вы можете изучить еще больше компонентов в компонентах каталога MDC-Android в MDC Android .

Что делать, если запланированный дизайн приложения содержит элементы, компоненты которых отсутствуют в библиотеке MDC? В MDC-104: Расширенные компоненты дизайна материалов мы рассмотрим, как создавать пользовательские компоненты с помощью библиотеки MDC для достижения определенного вида.

Я смог завершить эту лабораторную работу с разумным количеством времени и усилий.

Полностью согласен Соглашаться Нейтральный Не согласен Категорически не согласен

Я хотел бы продолжать использовать Material Components в будущем

Полностью согласен Соглашаться Нейтральный Не согласен Категорически не согласен