- Design Tools Suite UX enhancements in Android Studio 4.1
- Layout editor
- ConstraintHelpers support
- Design-time attributes toggle
- Visibility control on component tree
- Keyboard shortcuts + keymap settings
- Transform panel
- Resource manager
- Gutter drawable picker
- Vector asset icon auto-download
- Navigation editor
- New destinations tree
- Deeplink dialog new attributes + autocomplete
- Motion editor
- Motion keyframe path graph
- Transition curve editor
- Стилизация Android-приложений и дизайн-система: как это сделать и подружить одно с другим
- Компоненты дизайн-системы
- Проектирование, отладка и доработка компонентов дизайн-системы
- Способы внедрения темы в приложение
- Программный способ
- Недостатки
- Достоинства
- Стандартный механизм стилей в Android
- Примеры
- Стилизация компонентов дизайн системы. Архитектура компонентов. Поддержка нескольких тем
- Стандартный конструктор view
- Интеграция стиля в компоненты дизайн системы и его связь с темой
- Реализация темы в приложении
- Тестирование компонентов дизайн-системы
- Делаем рабочее preview компонентов дизайн-системы в Android Studio
- Preview компонентов в .xml
- Проверка поведения компонентов в другой теме в Preview без пересборки приложения
- Переключение тем в приложении
Design Tools Suite UX enhancements in Android Studio 4.1
The Design Tools Suite in Android Studio is a collection of tools that aims to support developers in effectively designing, prototyping, building, and debugging their apps. These tools include but are not limited to a Layout Editor, Navigation Editor, Motion Editor, Resource Manager, and Layout Inspector. With Android Studio 4.1, we’ve focused our efforts on the backlog of users’ (your) feedback to enhance these existing tools — as a result, we’ve refined interactions and created missing features. Here’s a round-up of what we’ve done — a closer look at the UX refinements mentioned in the What’s new in Design Tools Talk!
Layout editor
ConstraintHelpers support
ConstraintHelpers such as Barriers and Guidelines were first introduced in ConstraintLayout 1.1 to allow multiple widgets to be referenced as input of an invisible view, and group-align them without code duplication. In 2.0, the helpers concept was extended: VirtualLayouts such as Flow and Groups were added to allow for simultaneously applying behaviors to all referenced widgets. For example, with Flow, views can be easily laid out horizontally or vertically with global adjustments of gaps and wrap styles.
In Android Studio 4.1, we wanted to make sure our tools support and optimize the experience and interaction of using these helpers in the IDE. Thus, we first mapped out the user journey from discovery to creation to manipulation, and then we set out to increase efficiency for every step of the journey. For discovery, we added a helpers section in Palette so that it’s easy to find and use available helpers.
For creation, you can now also select multiple views, and right-click to select a helper — we then automatically add the referenced id’s corresponding to what was selected.
For manipulation, we wanted to make Flow’s functionality more accessible, so we expanded the property panel with commonly used attributes specific to Flow, such as icons for quick alignment and a section for rearranging the order of referenced id’s.
Design-time attributes toggle
Android Studio offers a variety of tools attributes, which are XML attributes in the android:tools namespace that enable design-time features (i.e., showing the layout of a fragment). These attributes are removed when you build your app and have no effect on APK size or runtime behavior — they are merely to aid in the design / development process.
For building UI, we know that tools:visibility and absolute positioning ( tools:layout_editor_absoluteX and tools:layout_editor_absoluteY) are two widely used tools attributes because they allow designers to temporarily show/hide UI as well as to position views precisely in the Layout Editor before setting constraints on them. However, we observed in user studies that it is difficult to know when and if views are set with tools attributes, such that users were surprised by discrepancies between the Layout Editor’s preview and the app’s rendering on an emulator or physical device. For example, in the screenshot below, the images in the right column have absolute positioning, and even though they look nicely laid out in the Layout Editor preview, in the emulator they’re all superimposed on one another in the top left corner.
To resolve this, we decided to add a toggle near the design surface in the Layout Editor to allow users to easily turn on/off tools:visibility and absolute positioning.
With the toggle, our goal is to provide users with a more accurate / non-design-time rendering and increased awareness about when they’re using these tools attributes.
Visibility control on component tree
Visibility, as stated in the last section, is a very common and important attribute for a view. It’s particularly useful when you need to show/hide certain UIs based on different conditions or certain logic. For example, you may only want authenticated users to be able to see their user data. Thus, we wanted to optimize the visibility attribute by providing a quick way to easily set show/hide/gone visibility in the Layout Editor.
Starting in 4.1, you will be able to use the visibility control picker in the component tree next to any view to quickly change it. This allows you to take one look at the tree and know how the views are shown based on visibility and change them according to whichever parts of the UI you would like to work on.
We included both the tools and android namespaces to accommodate different user needs. One thing to note here is that, during design-time, tools overrides android visibility, and thus this is reflected on the visibility controls as well — if you have a tools:visibility set, it will take precedence on the UI. For instance, in the screenshot below, the student image has an android:visibility = visible and tools:visibility = gone, and you can see that the tools visibility takes precedence.
Keyboard shortcuts + keymap settings
We all recognize the power of keyboard shortcuts in boosting productivity and efficiency for development. In Studio 4.1, we performed an audit of all the keyboard shortcuts in the Design Tools Suite and registered them in Preferences > Keymap, allowing you to discover, change, and edit the shortcuts to best fit your work style.
Transform panel
We’ve heard feedback from developers asking for more precision when manipulating transform attributes on a view. To make it easier to fine tune your view’s transformation, we added a visualizer and sliders to help with 3D rotation of views. On the attribute panel, once you’ve selected a view, you can use the controls under “Transform” to make adjustments.
Resource manager
Gutter drawable picker
Back in Android studio 3.6, we introduced the Color picker resource tab, which helps you quickly update color resource values in your app. The picker pattern was very well received since the interaction here provided a seamless transition from something textual (code) to something visual (colors) — users can stay in context within their code editor while using this graphical user interface (GUI) accelerator at the same time. Thus, in 4.1, we applied the same concept to Drawables — now when you have a drawable resource in your file, you will find a gutter icon that allows you to quickly change drawable resources. Moreover, clicking on “browse” will open the resource dialog allowing for more extensive search.
Vector asset icon auto-download
This update is perhaps not noticeable visually but is nevertheless significant. We received complaints about discrepancies between the Material icons on Material.io and those in our Vector Asset wizard. This was due to misalignment between Studio’s release cadence and updates to Material. To tackle this, we streamlined the process so that now every time Material updates their icon library, the Vector Asset wizard will also automatically update the library in the background. You can now expect we will always have the latest Material icons in the wizard! 🎉
Navigation editor
New destinations tree
Split View was introduced as a new way of switching editing modes for design files in Android Studio 3.6, and this created opportunities for us to optimize the side-by-side view for navigation files and the Navigation Editor. One of those optimizations is to use the component tree structure to represent the destination graph in the Navigation Editor. This way, users can see all their destinations (including nested ones) and actions at a glance, and they map 1:1 to the code in split mode.
As a side note, this was beneficial for the health of our code base as it reuses common components across all our design tools.
Deeplink dialog new attributes + autocomplete
Navigation 2.3.0 introduces two new attribute types for deeplinks: MIME and Action. To align the tools functionalities with that of the library, we added them to the creation dialog for deeplinks in the Navigation Editor, with autocomplete and validation support.
Motion editor
Motion keyframe path graph
MotionLayout supports different types of keyframes, and one of most commonly used types is Position keyframes ( ), which allows developers to modify the path of a widget at a given time during the animation. With the Motion Editor, introduced in 4.0, users can directly manipulate these keyframes by dragging them directly on the surface. However, a problem with this workflow is that, depending on how the keyframe is set up, the attributes applied to the keyframe can mean different things. For example, dragging the keyframe 20% to the left, there is no context of whether this is 20% relative to the path or 20% relative to the parent. To solve this, in 4.1 we added an overlay of the coordinate system as well as axis ghost objects on the design surface during drag, so that every time developers want to manually edit the keyframes, they can better understand their bounding, axis, and direction.
Transition curve editor
Similar to the Transform panel in the Layout Editor mentioned above, we have heard feedback from developers about how it’s difficult to specify Transition curves with pure numbers. Thus, in 4.1, we added support for a GUI curve editor in the Motion Editor, allowing developers to perfect the curves with visualization and control handles.
We hope that you are excited to try out these new improvements! We are constantly gathering feedback and applying them to improve our tools. The goal of the Design Tools Suite is to support, supplement, and boost your coding experience — to find areas where it makes sense to provide visual or GUI support. The learnings we uncovered here will also be applied to tools we build for Jetpack Compose. For instance, these pickers experiences (i.e., visibility toggle, gutter drawable pickers) are a form factor that we can further explore, since they are context-based, non-distracting, and provide a unique way to apply design tooling to the app development process.
As always, if you encounter any issues while using these tools, or have an idea for new features that can improve your productivity, please file a bug. We will continue to optimize the editors’ performance, fix bugs, and incorporate your suggestions and feedback.
Источник
Стилизация Android-приложений и дизайн-система: как это сделать и подружить одно с другим
В какой-то момент любое крупное приложение разрастается так, что сложно везде поддерживать однотипный дизайн и динамично реагировать на любые изменения и тенденции в дизайне и UX-требованиях.
Поэтому решили внедрить в наше приложение дизайн-систему и добавить поддержку нескольких тем оформления.
Изучив различные способы, выработали свой подход к решению такой задачи. Хотелось сделать так, чтобы дизайн-систему и поддержку стилей можно было повторно использовать в других своих проектах. В соответствии с этой идеей разрабатывались компоненты и темы.
Компоненты дизайн-системы
Дизайн-система и её компоненты предназначены для унификации дизайна и стилевого единства во всем приложении.
Компонентами дизайн-системы в нашем случае будем называть custom view с возможностью адаптации к нескольким стилям приложения. Компоненты могут применяться в любом месте приложения (кнопки, элементы списка, заголовки и т.д.).
Проектирование, отладка и доработка компонентов дизайн-системы
Заказчиками компонентов дизайн-системы являются дизайнеры. С ними на первом этапе согласовываем надобность элемента (оценка переиспользуемости) и его функциональность.
После согласования должно быть понятно, какие опции нужно вынести в атрибуты custom view (цвет текста, текст, иконочку, цвет тинта иконочки и т.д.), а какие скрыть от изменений извне (это позволяет уберечь элемент от неправильного использования разработчиками).
Далее дизайнеры отрисовывают компонент в своих средах и отдают на разработку.
При реализации компонента нужно добавить поддержку тем (светлая или темная тема и т.д.) О том, как компонент поддерживает несколько тем, я расскажу ниже.
Лучшие методики
- Создать модуль с компонентами дизайн-системы. Из положительных моментов: отдельный модуль может быть использован в других приложениях, а модульность позволяет быстрее ориентироваться.
- Создать тестовое приложение с компонентами дизайн-системы. Это ускоряет разработку и отладку.
Способы внедрения темы в приложение
Мне известно два способа поддержки стилей в Android:
- Программный (программная перекраска).
- Стандартные механизмы стилей в Android.
Программный способ
Мы перекрашиваем всю иерархию view в runtime. Рекурсивно проходимся по ней и по определенным правилам перехода из одной темы в другую перекрашиваем компоненты. Те из них, которые не должны перекрашиваться, маркируются с помощью android:tag или android:contentDescription . Эти компоненты не учитываются при разборе иерархии экрана.
Перекрашивать можно как перед отображением экрана (например, в onStart() у Activity ), так и при работе с ним.
Недостатки
- Требует дополнительных ресурсов, снижает производительность. Стилизация применяется после инициализации всех компонентов.
- Нужно быть внимательным к правилам перехода из одной темы в другую. Требуется учесть огромное множество правил перекраски, можно что-то забыть. Получается длинная простыня из switch — case (Java) или when (Kotlin). И в довесок требуется учесть элементы, которые не нужно красить при помощи вышеупомянутых тегов.
- Нельзя частично перекрасить в соответствии с темами. В любом правиле есть исключения, и не всегда всё в приложении делается по дизайн-системе. Непонятно, как действовать если требуется частичная перекраска некоторых элементов.
Применение стиля сводится к описанию изменений в конкретных элементах:
Достоинства
Не требует пересоздания Activity (это важно! Нет морганий при смене темы).
Я внедрил этот подход в одном известном всем продукте (см. скриншоты). Работает довольно быстро при простой однотипной вёрстке(в данном случае она была простая).
Стандартный механизм стилей в Android
Стиль — локальная стилизация экрана или view, затрагивающая только отдельный экран или view. Часто такую стилизацию называют «ThemeOverlay», или «легковесная» тема, которая позволяет переопределить атрибуты основной темы).
Тема — глобальная стилизация экранов приложения, затрагивающая подмену стилей, цветов и т.д. у всего, что мы видим на экранах приложения.
Темой можно считать множество стилизаций, которые можно переключать.
Примеры
В теме могут содержаться как стили конкретных view элементов, так и конкретные цвета.
Здесь объявлен стиль для конкретной view:
Стили поддерживают явное и неявное наследование:
- Явное: Header1 унаследован от BaseTextWidget .
- Неявное: Header1.Light унаследован от Header1 .
Если к текстовому элементу мы применим стиль Header1 , то подтянется только Header1 . А атрибуты Header1.Light или Header1.Dark не применятся.
Если к текстовому элементу мы применим стиль Header1.Light / Dark , то подтянутся стили Header1.Light / Dark и Header1 (достоинство неявного наследования)
Множественного наследования темы не поддерживают. Вероятно, из-за конфликтов одноименных атрибутов.
Стили каждого компонента дизайн-системы мы решили размещать в файлах attrs_component_name.xml (см. attrs_header1 , attrs_button и т.д.)
Стилизация компонентов дизайн системы. Архитектура компонентов. Поддержка нескольких тем
Стандартный конструктор view
Стандартный конструктор view предоставляет обширные средства для настройки элемента. Внешний вид элементов можно изменить через .xml-атрибуты или через определение стиля по умолчанию в стандартном конcтрукторе view.
Рассмотрим стандартный конструктор view на примере H1Component (задаёт крупный текст в шапке экранов):
Здесь attrs — атрибуты из определения .xml (в том числе кастомные атрибуты view). Они парсятся и применяются стандартным образом (см. ниже на примере FabComponent ).
defStyleAttr — стиль view по умолчанию.
context — контекст view, при помощи которого она создана.
ВАЖНО: чтобы view успешно переключала тему, необходимо чтобы она была создана при помощи контекста, унаследованного от android.view.ContextThemeWrapper (то есть контекст activity подходит, а applicationContext — не подходит (применится тема, которая подтянется из стиля, указанного в Manifest экрана).
ВАЖНО: при такой реализации главный приоритет у атрибутов, объявленных в .xml. У стилей, описанных в теме, приоритет ниже.
Интеграция стиля в компоненты дизайн системы и его связь с темой
Для поддержки темы компонентами дизайн-системы мы определяем в компонентах defStyleAttr и переключаем его в соответствии с темой, в которой он определен.
Реализация темы в приложении
Создаем две темы:
Компоненты дизайн системы системы будут тянуть этот стиль в таком ключе:
Тут определены стили каждой темы для этого элемента:
Применяем тему через стандартный механизм Android.
При создании Activity указываем нужную тему. Тогда MyBestText подтянет нужный стиль и окрасит свой текст в белый или черный в зависимости от темы (см. выше описание темы MyBestText ).
Цвета из темы мы будем разрешать прямо из .xml и подтягивать из темы.
ВАЖНО: начиная с Android 5.0 допускается отовсюду динамически разрешать android:background=»?attr/primary_background» (селекторы, shape, vector drawables и т.д.) В Android 4.4 есть ограничение на селекторы, при попытке динамически разрешить итоговый цвет из селекторов система упадёт.
При всех достоинствах такой реализации компоненты дизайн-системы не могут в preview Android Studio полноценно работать со стилизованными темами (к элементам не будут применяться стили).
Пока тема официально не использована нашими экранами, а только подключается программно (то есть стили наших activity не подгружают явным образом тему из Manifest ), мы не можем комфортно работать с элементами, поддерживающими темы в preview (их даже не будет в списке).
Тестирование компонентов дизайн-системы
Для тестирования и анализа степени покрытия приложения дизайнеры предложили разработать отладочную панель с настройками стилей компонентов, цветов и т.д.
Темы в Android являются неизменяемыми, но их всегда можно перезаписать полностью или частично через Activity.setTheme ( @StyleRes final int resid ). Так можно в нужный момент получить любую комбинацию стилей и собрать свою собственную тему. Но все стили должны быть объявлены в .xml заранее.
Программно изменять атрибут темы без отсылок к объявленным стилям, к сожалению, нельзя. По крайней мере, я не нашёл способа.
Если знаете, как подсунуть свой цвет в атрибут темы (не объявленный в ресурсах как style ), то напишите мне. Тогда мы сможем прямо из коробки манипулировать цветами с бэка на уровне стилизации всего приложения!
Делаем рабочее preview компонентов дизайн-системы в Android Studio
Темы экранов приложения должны наследоваться от темы дизайн-системы.
Preview компонентов в .xml
При некорректно установленной теме экрана компоненты дизайн-системы тоже не будут отображаться корректно (не применятся стили и цвета):
При установке темы, унаследованной от темы дизайн-системы, мы получим вот что:
Видно, как разрешились все атрибуты темы и правильно подтянулись стили компонента.
Проверка поведения компонентов в другой теме в Preview без пересборки приложения
Чтобы проверить отображение в другой теме достаточно переключить тему в Preview light/dark.
Если конкретные реализации темы завязаны на ресурсы values/values-night, то можно переключать из preview в dark mode. И всё будет работать из коробки без выставления setTheme в Activity .
Переключение тем в приложении
Переключение тем в приложении может быть завязано на системное переключение dark-mode. В таком случае темы должны быть определены в директориях values и values-night.
Источник