- Material Design for Android
- Developer Docs
- Video
- Video
- Video
- Material Theme
- Lists and Cards
- View Shadows
- Animations
- Drawables
- Material 2.0 для разработчиков. Краткий обзор новых компонентов
- Android X вместо Support library
- Material library
- BottomAppbar
- Chips
- BackDrop
- MaterialButtons
- Text Fields
- MaterialCardView
- Итого
- Material design java android
Material Design for Android
Developer Docs
Creating Apps with Material Design
Video
Introduction to Material Design
Video
Paper and Ink: The Materials that Matter
Video
Material Design in the Google I/O App
Material design is a comprehensive guide for visual, motion, and interaction design across platforms and devices. Android now includes support for material design apps. To use material design in your Android apps, follow the guidelines defined in the material design specification and use the new components and functionality available in Android 5.0 (API level 21) and above.
Android provides the following elements for you to build material design apps:
- A new theme
- New widgets for complex views
- New APIs for custom shadows and animations
For more information about implementing material design on Android, see Creating Apps with Material Design.
Material Theme
The material theme provides a new style for your app, system widgets that let you set their color palette, and default animations for touch feedback and activity transitions.
Dark material theme
Light material theme
Lists and Cards
Android provides two new widgets for displaying cards and lists with material design styles and animations:
The new RecyclerView widget is a more pluggable version of ListView that supports different layout types and provides performance improvements.
The new CardView widget lets you display important pieces of information inside cards that have a consistent look and feel.
View Shadows
In addition to the X and Y properties, views in Android now have a Z property. This new property represents the elevation of a view, which determines:
- The size of the shadow: views with higher Z values cast bigger shadows.
- The drawing order: views with higher Z values appear on top of other views.
Animations
The new animation APIs let you create custom animations for touch feedback in UI controls, changes in view state, and activity transitions.
These APIs let you:
- Respond to touch events in your views with touch feedback animations.
- Hide and show views with circular reveal animations.
- Switch between activities with custom activity transition animations.
- Create more natural animations with curved motion.
- Animate changes in one or more view properties with view state change animations.
- Show animations in state list drawables between view state changes.
Touch feedback animations are built into several standard views, such as buttons. The new APIs let you customize these animations and add them to your custom views.
Drawables
These new capabilities for drawables help you implement material design apps:
- Vector drawables are scalable without losing definition and are perfect for single-color in-app icons.
- Drawable tinting lets you define bitmaps as an alpha mask and tint them with a color at runtime.
- Color extraction lets you automatically extract prominent colors from a bitmap image.
Источник
Material 2.0 для разработчиков. Краткий обзор новых компонентов
В мае на Google I/O мы впервые увидели Material Design 2.0. Команда Google провела крупный рефакторинг и выпустила обновленную библиотеку дизайна. В ней появились новые компоненты и анимации. Мы следим за развитием Material Components с самого начала. Сейчас все находится на стадии RC1, и уже скоро выйдет в релиз. Под катом обзор новых и обновленных UI-компонентов для тех, кто еще не пробовал их в работе, но интересуется.
Android X вместо Support library
«Как это уже задеприкейтили? Я даже попробовать ее толком не успел», – сказал один мой знакомый, когда узнал о переезде Material Components в новый пакет. Действительно, поддержки support.design больше не будет, а на ее место придет com.google.android.material.
В рамках проекта Android X Google устроили рефакторинг всей библиотеки поддержки и архитектурных компонентов. Подробнее можно почитать в их блоге. Вот пример некоторых пакетов:
старый пакет
новый пакет
androidx.@
androidx.databinding.@
com.google.android.material.@
К счастью, для «мягкого» переезда на новую библиотеку, в студии появится инструмент, позволяющий автоматически обновить все зависимости. Сейчас это доступно уже в Android Studio Canary 3.3. Он призван автоматически находить все зависимости в импортах, в gradle файлах, в XML и в Proguard.
Material library
Все старые UI-компоненты из Support Library переехали в Material library, а ещё появились новые компоненты. Добавим в проект новую зависимость:
Обратной совместимости с Support не предполагается. Придется избавиться от всех остальных зависимостей, где встречается слово support, и заменить их на соответствующие из Android X. Иначе проект просто не соберется из-за множества конфликтов. Для тестовой сборки мне пришлось даже заменить Glide на Picasso, потому что первый тянет за собой android-support. На большом проекте вручную это делать будет неудобно.
Однако для тестирования Material Components можем воспользоваться support:design версии 28-beta, куда Google любезно продублировала все актуальные компоненты. Несмотря на это, 28 версия Support library будет последней, и в дальнейшем ее поддержка прекратится. А теперь давайте посмотрим на новые компоненты, и измененные старые.
BottomAppbar
BottomAppbar – это что-то похожее на Appbar, только с возможностью прикрепления Floating Action Button и вырезом под него. Предназначен для работы внутри CoordinatorLayout.
Вот некоторые параметры, которые мы можем кастомизировать:
- app:backgroundTint — цвет заполненного пространства
- app:fabAlignmentMode — положение FAB
- app:fabCradleMargin — отступ между FAB и BottomAppbar
- app:fabCradleRoundedCornerRadius — закругление на углах выреза для FAB
- app:fabCradleVerticalOffset
- app:hideOnScroll
На момент написания статьи, BottomAppBar доделан не до конца. Например, нельзя разместить NavigationIcon в центре по вертикали, но, наверное, это скоро допилят.
Chips
Chip – еще одна новая View в библиотеке. С её помощью можно удобно показывать перечисление небольших объектов. Например, фильтры или какие-нибудь подсказки для пользователя. По гайдлайнам Chip обладает следующими свойствами:
- Может иметь иконку контента (слева).
- Может иметь иконку для удаления (справа).
- Содержит текст.
- Может находится в двух состояниях, как CheckBox.
Реализация в Material library представляет из себя расширенную версию AppCompatCheckBox, и может порадовать нас такими кастомизируемыми параметрами:
- app:chipCornerRadius
- app:chipMinHeight
- app:chipBackgroundColor
- app:chipStrokeColor
- app:chipStrokeWidth
- app:rippleColor
- android:text
- android:textAppearance
- app:chipIconVisible
- app:chipIcon
- app:chipIconTint
- app:chipIconSize
- app:closeIconVisible
- app:closeIcon
- app:closeIconSize
- app:closeIconTint
- app:checkable
- app:checkedIconVisible
- app:checkedIcon
- app:showMotionSpec
- app:hideMotionSpec
Приятно удивило наличие ChipGroup, являющегося наследником FlexboxLayout, которого наконец-то включили в библиотеку дизайна.
BackDrop
BackDrop – новый для Android паттерн навигации. Есть основной контент, который расположен на переднем плане, и дополнительная область, лежащая позади (обычно это меню навигации). Если нужно добраться до контента сзади, то передний план съезжает вниз до нужного уровня.
Состоит Backdrop из трех элементов:
На момент написания статьи он еще не реализован в библиотеке, и в соответствующем репозитории пока пусто. Поэтому пришлось делать свою реализацию, обернув ее в библиотеку:
Просто прикрепляем BackdropBehavior на нужный Front Container и передаем ему Toolbar и Back Container.
XML
Kotlin
Это просто один из вариантов реализации. Но для моего кейса получилось удобно. Думаю, решение Google будет несколько отличаться. Если вдруг есть предложения, то с радостью готов обсудить их в комментариях под статьей.
MaterialButtons
MaterialButtons – обновленные более кастомизируемые кнопки. У них есть следующие параметры для кастомизации:
- android:inset (Left, Top, Right, Bottom) — отступ кнопки от края View
- app:backgroundTint — цвет заполнения кнопки
- app:backgroundTintMode
- app:icon — можно добавить иконку, по умолчанию слева от текста
- app:iconPadding
- app:iconTint
- app:iconTintMode
- app:strokeColor — для создания кнопок с обводкой
- app:strokeWidth
- app:cornerRadius
- app:rippleColor
Конечно, эти стили для кнопок всегда можно сделать самостоятельно. Но теперь кастомизация кнопок хорошо работает «из коробки», и это очень удобно.
Например, чтобы сделать кнопку с крестиком, раньше пришлось бы писать два XML файла:
Layout:
bg_button.xml
Теперь описать кнопку можно сразу на месте:
Text Fields
Text Fields – тоже претерпел изменения. Теперь текстовому полю «из коробки» можно добавить обводку по контуру, сделать его залитым каким-то цветом, или закруглить отдельные углы.
Как и раньше, можно использовать конструкцию из InputLayout с дочерним EditText, для более удобного для отображения подсказок, ошибок и прочего выделения текста.
- app:boxCornerRadiusTopLeft
- app:boxCornerRadiusTopRight
- app:boxCornerRadiusBottomLeft
- app:boxCornerRadiusBottomRight
- android:hint
- app:hintEnabled
- app:errorEnabled
- app:setError
- app:helperTextEnabled
- app:helperText
- app:passwordToggleEnabled
- app:passwordToggleDrawable
- app:counterEnabled
- app:counterMaxLength
Изменения тоже не очень существенные, но кастомные решения можно разрабатывать теперь намного быстрее. С точки зрения бизнеса, скорость разработки имеет значение, и тут Google постарались неплохо.
MaterialCardView
MaterialCardView – это все старая CardView, но теперь с обводкой по контуру, как у кнопок.
Итого
Существенных изменений не так много. Новые механизмы кастомизации просто позволяют сделать чуточку проще то, что мы все делали и раньше. Зато появилась проблема совместимости с Support library. Разработчикам библиотек придется переезжать на Android X, что отнимет много времени и нервов. Особенно, если учесть, какая кодовая база сейчас support-ориентированна. Несмотря на то, что Google предоставляет инструмент для автоматизации переезда с заменой всех импортов, работает он не идеально. Подобные переезды на своих проектах все-таки придется пережить с некоторыми трудностями.
На данный момент не все заявленные Material-компоненты реализованы корректно, а некоторые не реализованы совсем. Будем смотреть, будем пробовать.
Источник
Material design java android
Copy raw contents
Getting started with Material Components for Android
1. Migration guidance
Take a look at our guide and codelab to help you migrate your codebase using Material Components for Android to the new Material 3 system.
Additionally, if you are still using the legacy Design Support Library, take a look at our legacy guide to help you migrate your codebase to Material Components for Android.
2. Maven library dependency
Material Components for Android is available through Google’s Maven Repository. To use it:
Open the build.gradle file for your application.
Make sure that the repositories section includes Google’s Maven Repository google() . For example:
Add the library to the dependencies section:
Visit Google’s Maven Repository or MVN Repository to find the latest version of the library.
Note: In order to use the new Material3 themes and component styles, you must depend on version 1.5.0-alpha04 or later.
New Namespace and AndroidX
If your app currently depends on the original Design Support Library, you can make use of the Refactor to AndroidX… option provided by Android Studio. Doing so will update your app’s dependencies and code to use the newly packaged androidx and com.google.android.material libraries.
If you don’t want to switch over to the new androidx and com.google.android.material packages yet, you can use Material Components via the com.android.support:design:28.0.0 dependency.
Note: You should not use the com.android.support and com.google.android.material dependencies in your app at the same time.
3. Android 12 compilation
In order to use the latest versions of Material Components for Android and the AndroidX Jetpack libraries, you will have to install the latest version of Android Studio and update your app’s compileSdkVersion to 31 .
As part of migrating to Android 12, you’ll need to add android:exported to any activities, services, or broadcast receivers in your manifest that use intent filters (see the documentation). Consider reading through the Android 12 app migration guide and behavior changes for more tips and information.
4. Java 8 compilation
The latest AndroidX Jetpack libraries now require your app to be compiled with Java 8. See the Java 8 language features and APIs documentation for more information on Java 8 support and how to enable it for your app.
Use AppCompatActivity to ensure that all the components work correctly. If you are unable to extend from AppCompatActivity , update your activities to use AppCompatDelegate . This will enable the AppCompat or Material versions of components to be inflated (depending on your theme), among other important things.
6. Material3 theme inheritance
We recommend you perform an app-wide migration by changing your app theme to inherit from a Material3 theme. Be sure to test thoroughly afterwards, since this may change the appearance and behavior of existing layout components.
Check out the new Material Theme Builder which can be used to generate your Material3 app theme, with all of the Material Color System roles filled out based on your brand colors.
Note: If you can’t change your theme, you can continue to inherit from an AppCompat or MaterialComponents theme and add some new theme attributes to your theme. See the AppCompat or MaterialComponents themes section for more details.
Material3 themes
Here are the Material3 themes you can use to get the latest component styles and theme-level attributes, as well as their MaterialComponents equivalents when applicable.
Material3 | MaterialComponents |
---|---|
Theme.Material3.Light | Theme.MaterialComponents.Light |
Theme.Material3.Light.NoActionBar | Theme.MaterialComponents.Light.NoActionBar |
Theme.Material3.Dark | Theme.MaterialComponents |
Theme.Material3.Dark.NoActionBar | Theme.MaterialComponents.NoActionBar |
Theme.Material3.DayNight | Theme.MaterialComponents.DayNight |
Theme.Material3.DayNight.NoActionBar | Theme.MaterialComponents.DayNight.NoActionBar |
N/A | Theme.MaterialComponents.Light.DarkActionBar |
N/A | Theme.MaterialComponents.DayNight.DarkActionBar |
Update your app theme to inherit from one of these themes:
For more information on how to set up theme-level attributes for your app, take a look at our Theming guide, as well as our Dark Theme guide for why it’s important to inherit from the DayNight theme.
Material3 themes enable a custom view inflater, which replaces default components with their Material counterparts. Currently, this replaces the following XML components:
AppCompat or MaterialComponents Themes
You can incrementally test new Material components without changing your app theme. This allows you to keep your existing layouts looking and behaving the same, while introducing new components to your layout one at a time.
However, you must add the following new theme attributes to your existing app theme, or you will encounter ThemeEnforcement errors:
7. Add Material components
Take a look at our documentation for the full list of available Material components. Each component’s page has specific instructions on how to implement it in your app.
Let’s use text fields as an example.
Implementing a text field via XML
The default outlined text field XML is defined as:
Note: If you are not using a theme that inherits from a Material3 theme, you will have to specify the text field style as well, via style=»@style/Widget.Material3.TextInputLayout.OutlinedBox»
Other text field styles are also provided. For example, if you want a filled text field in your layout, you can apply the Material3 filled style to the text field in XML:
Material Components for Android welcomes contributions from the community. Check out our contributing guidelines as well as an overview of the directory structure before getting started.
Источник