Компоненты Material (MDC) помогают разработчикам реализовывать принципы Material Design. MDC, созданный командой инженеров и UX-дизайнеров Google, включает в себя десятки красивых и функциональных компонентов пользовательского интерфейса и доступен для Android, iOS, веб-приложений и Flutter. material.io/develop |
В практических занятиях 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/kotlin
. Перед началом работы обязательно 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
- После завершения работы мастера настройки и появления окна «Добро пожаловать в Android Studio» нажмите « Открыть существующий проект Android Studio» . Перейдите в каталог, куда был установлен пример кода, и выберите kotlin -> shrine (или найдите shrine на компьютере), чтобы открыть проект Shipping.
- Подождите немного, пока Android Studio выполнит сборку и синхронизацию проекта, на что указывают индикаторы активности в нижней части окна Android Studio.
- На этом этапе Android Studio может выдать ошибки сборки, поскольку у вас отсутствует Android SDK или инструменты сборки, например, показанные ниже. Следуйте инструкциям Android Studio, чтобы установить/обновить их и синхронизировать свой проект.
Добавить зависимости проекта
Проекту требуется зависимость от библиотеки поддержки MDC для Android . В загруженном примере кода эта зависимость уже должна быть указана, но для её обеспечения рекомендуется выполнить следующие шаги.
- Перейдите к файлу
build.gradle
модуляapp
и убедитесь, что блокdependencies
включает зависимость от MDC Android:
api 'com.google.android.material:material:1.1.0-alpha06'
- (Необязательно) При необходимости отредактируйте файл
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' }
Запустите стартовое приложение
|
Успешно! На вашем устройстве или эмуляторе должна появиться страница входа Shrine. После нажатия кнопки «Далее» откроется главная страница Shrine с панелью приложений вверху и сеткой изображений продуктов внизу.
Давайте сделаем так, чтобы верхняя панель приложений соответствовала бренду Shrine, изменив ее цвет, высоту и шрифт.
Эта цветовая тема создана дизайнером с использованием собственных цветов (показано на изображении ниже). Она содержит цвета, выбранные из фирменного стиля Shrine и примененные в редакторе тем Material, который расширил их, создав более полную палитру. (Эти цвета не входят в палитры Material 2014 года .)
Редактор тем Material Theme упорядочил их по оттенкам с числовыми обозначениями, включая обозначения 50, 100, 200 и т. д. до 900 для каждого цвета. Shrine использует только оттенки 50, 100 и 300 из розового образца и 900 из коричневого образца.
Давайте изменим цвет верхней панели приложения, чтобы он отражал эту цветовую схему.
Установить цветPrimaryDark и цветAccent
В colors.xml
измените следующие строки. Атрибут colorAccent
, помимо прочего, управляет цветом верхней панели приложения, а атрибут colorPrimaryDark
— цветом строки состояния.
colors.xml
<color name="colorPrimaryDark">#FBB8AC</color>
<color name="colorAccent">#FEDBD0</color>
Чтобы использовать темные значки в строке состояния, добавьте следующее в Theme.Shrine
, тему приложения Shrine:
стили.xml
<item name="android:windowLightStatusBar" tools:targetApi="m">true</item>
<resources xmlns:tools="http://schemas.android.com/tools">
Ваши colors.xml
и styles.xml
должны выглядеть следующим образом:
colors.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
, чтобы задать
атрибут цвета textColorPrimary
, который мы только что определили.
И еще одно: установите атрибут android:theme
в стиле Widget.Shrine.Toolbar
на Theme.Shrine
.
Ваши colors.xml
и styles.xml
должны выглядеть следующим образом:
colors.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
:
colors.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>
Наконец, задайте атрибут 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
. Откройте файл с файлом и измените значение свойства android:fillAlpha
на 1. Изображение должно выглядеть следующим образом:
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
должны выглядеть следующим образом:
colors.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-компонентам NestedScrollView
в shr_product_grid_fragment.xml
следующим образом:
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.recyclerview.widget.RecyclerView
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.android.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
заставляет кнопку «Далее» использовать предоставленный нами аниматор.
Выполните сборку и запустите. Ваш экран входа должен выглядеть так:
Давайте изменим макет, чтобы показать карточки с разным соотношением сторон и размером, чтобы каждая карточка отличалась от других.
Используйте ступенчатый адаптер RecyclerView
Мы предоставили вам новый адаптер RecyclerView
в пакете staggeredgridlayout
, который отображает асимметричный макет карточек со смещением и горизонтальной прокруткой. Вы можете самостоятельно изучить этот код, но мы не будем здесь подробно рассматривать, как он реализован.
Чтобы использовать этот новый адаптер, измените метод onCreateView()
в ProductGridFragment.kt
. Замените блок кода после комментария «set up the RecyclerView
» следующим кодом:
ProductGridFragment.kt
// Set up the RecyclerView
view.recycler_view.setHasFixedSize(true)
val gridLayoutManager = GridLayoutManager(context, 2, RecyclerView.HORIZONTAL, false)
gridLayoutManager.spanSizeLookup = object : GridLayoutManager.SpanSizeLookup() {
override fun getSpanSize(position: Int): Int {
return if (position % 3 == 2) 2 else 1
}
}
view.recycler_view.layoutManager = gridLayoutManager
val adapter = StaggeredProductCardRecyclerViewAdapter(
ProductEntry.initProductEntryList(resources))
view.recycler_view.adapter = adapter
val largePadding = resources.getDimensionPixelSize(R.dimen.shr_staggered_product_grid_spacing_large)
val smallPadding = resources.getDimensionPixelSize(R.dimen.shr_staggered_product_grid_spacing_small)
view.recycler_view.addItemDecoration(ProductGridItemDecoration(largePadding, smallPadding))
Нам также потребуется внести небольшое изменение в наш shr_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.kt
. Измените метод getItemOffsets()
в ProductGridItemDecoration.kt
следующим образом:
ProductGridItemDecoration.kt
override fun getItemOffsets(outRect: Rect, view: View,
parent: RecyclerView, state: RecyclerView.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.kotlin.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
, как показано ниже:
colors.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].
Что делать, если ваш проект приложения содержит элементы, которых нет в библиотеке MDC? В курсе MDC-104: Расширенные компоненты Material Design мы рассмотрим, как создавать пользовательские компоненты с помощью библиотеки MDC для достижения определённого внешнего вида.