- Introduction to Android Design Patterns
- Android Design Principles
- Standard Android Interface Themes
- Application Icons
- Interaction Design
- Differences Between Android & iOS
- Fixed Tabs
- Drop-Down Menu
- Back & Up
- Widgets
- Exploring Design Patterns
- Conclusion
- Архитектура Android-приложений. Часть II — архитектурные стили и шаблоны
Introduction to Android Design Patterns
Previously, you learned about design patterns and how they applied to the iOS platform. In this article, we take a closer look at design patterns on the Android platform and they differ from design patterns on iOS. If you’re unfamiliar with design patterns on Android, then this article is for you.
If you haven’t read my previous article about design patterns on iOS, then I encourage you to take a few minutes to read that article before continuing. Some of the concepts and terminology used in this article were introduced in Introduction to iOS Design Patterns.
Android Design Principles
Every operating system or platform has guidelines for design. Consistent design helps to create a distinct look and feel for the operating system or platform. When you’re working on an application that will target both iOS and Android, for example, you’ll learn that there are a number of subtle—and not so subtle—differences regarding the vision that underlies the design. These are some examples of aspects which are emphasized differently than other mobile operating systems.
- Personalization: The Android guidelines recommend that you include a level of personalization within an application as it helps make users feel at home. Giving the user the ability to theme an application is a good example of this concept.
- Icons Over Words: If you can communicate something through visuals, such as icons or images, then that should be the preferred method of communication. If you come across a scenario in which words are absolutely necessary, then make sure to keep it concise and actionable.
- Every User Is An Expert: Mobile applications should always be easy to use. At the same time, you should give the user the impression that they’re a power user. This can be accomplished by providing shortcuts or by implementing a powerful onboarding process.
Standard Android Interface Themes
As a starting point, the Android platform currently provides two standard themes when you want to design applications for the platform. These themes are useful and recommended when you’re just starting out, but they are by no means mandatory.
The themes are called Holo Light and Holo Dark, a light and a dark theme, depending on the visual style you aim to achieve in your application.
Using one of the standard themes will help you when you’re just starting out and learning more about Android’s design patterns. Because the standard themes are a part of Android, you start from a solid foundation that conforms to the standards of the operating system. It’s also a great starting point for custom designs.
Application Icons
Of course, it’s not just about the application’s interface. Even since flat design became popular on iOS, a clear difference has emerged between application icons on Android and iOS.
Most Android applications have application icons that create a sense of depth to mimic the real world. Many application icons on Android have a subtle 3D effect applied to them to create that sense of depth. Another noticeable difference between icons on Android and iOS is the use of transparency.
If you’re developing an application that target both Android and iOS, then it’s important to create a concept that works well on both platforms.
Interaction Design
When a user interacts with an application’s user interface, she expects some form of visual feedback. This feedback is generally more explicit on Android than it is on iOS.
Visual feedback is great for improving the user experience, because it creates a feeling of responsiveness and control, which are two aspects users have come to expect of mobile applications.
I encourage you to download some of the popular applications of each platform and explore how they respond to your input.
Differences Between Android & iOS
It shouldn’t be a surprise that a number of components are unique to or different on the Android platform.
Note that these are just a few examples. The best advice I can give you when you’re creating an application for a platform you’re not familiar with is to get input from users and developers who are familiar with the platform. They can quickly point out what feels odd or wrong and what isn’t.
Fixed Tabs
In iOS, a tab bar is usually found at the bottom of the screen in an application’s user interface. In Android, however, tabs are positioned at the top. Android supports multiple and scrollable tabs while iOS has specific guidelines in which use cases tabs are a good fit and the guidelines even specify the maximum number of tabs.
The result is that a user interface designed for the Android platform may not always work on iOS due to technical limitations. Scrollable tabs, for example, are unique to Android and not supported by the iOS SDK.
Drop-Down Menu
A drop-down menu is something you only find on Android. There are different use case in which a drop-down menu is a good fit. When you have many functionalities or a lot of content groups with inconsistent navigation, a drop-down menu is a viable solution to tackle the problem.
Back & Up
Since Android 4.0, there is a sticky navigation bar at the bottom of the screen. Apart from the recent button, the navigation bar also contains a back and up button. Tapping back bring the user to the previous screen while tapping up brings you to the upper level in the application’s hierarchy.
For example, I could be swiping through different pieces of content in an application. The back button would bring me back to the previous item while tapping up would navigate me to the selection menu from which I’m able to select a new item. This is a powerful feature, which you should take into account while creating the information architecture of an application.
In Android, you generally don’t see custom back buttons like the ones we usually see in the navigation bar in iOS applications.
Widgets
Android also supports widgets, which are completely absent on the iOS platform.
Exploring Design Patterns
Let’s dive deeper in some of the design patterns on Android. In general, the best practices to create a user interface is to see how other applications solve a particular design problem and how standard interface elements can solve it.
For example, how do other applications display content? How do they handle user input? Or implement e-commerce? By looking at a few examples, you get an idea of the possible solutions to solve the design problem you’re facing. Does this mean you should blatantly copy an existing application? Not really.
A well thought out app tries to solve a specific problem. Usually, your app tries to tackle a unique problem, which means that you need to figure out a suitable user flow.
The following list should give you an introduction to think about possible design patterns for your application:
- Show, don’t tell. Teaching users about the functionalities of your app should happen through actions rather than telling users. In general, tutorials should be avoided if possible.
- Focus. A screen should preferably have a single goal from the user’s perspective.
- Encourage the exploration of diverse features through efficient navigation. Open five applications and see how each implements navigation. Learn the benefits and downsides of each implementation.
- Define the data model and user flow before building and designing your application.
- When building a new application, search for similar applications to learn from. What does the user flow look like? How is the user interface designed and how can it be improved?
- Applying design patterns boils down to thinking abstractly about building the most efficient application with a strong focus on the user flow and interface.
- Involve Android users in the design process to get early feedback and a fresh look on the current state of your design.
Conclusion
Learning more about Android design patterns means that you need to become more familiar with the Android platform. Creating a user interface that closely resembles the standards of the operating system means users have a greater sense of familiarity and an improved user experience.
Keep in mind that we only briefly touched the subject. There are many resources available that will help you improve your understanding of design patterns on Android. However, you learn most by creating user flows and user interfaces.
Источник
Архитектура Android-приложений. Часть II — архитектурные стили и шаблоны
В этой статье мы поговорим об архитектурных шаблонах, используемых в Android-приложениях.
Почему важно понимание шаблонов, реализованных в рамках некой архитектуры? Потому что таким образом изучаемая нами новая архитектура укладывается в контекст нашего предыдущего опыта и позволяет нам более эффективно использовать накопленные знания и навыки.
Возможно, я плохо искал, но в документации Android нет упоминания о каких-либо шаблонах. Не смотря на это, в Android реализованы некоторые шаблоны и архитектурные стили, о которых мы сейчас и поговорим.
Архитектура Android является фреймворк-ориентированной (framework-based), в противовес вольной (free-style) архитектуре.
В чём разница? Вольные приложения, написанные на Java, начинаются с класса, имеющего метод main(), и разрабатываются в полном соответствии с настроением разработчика.
В противоположность этому фреймворк-ориентированные приложения основываются на существующем фреймворке. Их разработка сводится к расширению неких классов или реализации интерфейсов, предоставленных фрейморком. Такое приложение не может быть запущено вне фреймворка или без него. Примером могут быть веб-приложения на Java, в которых разработчики реализуют интерфейс Servlet или расширяют одну из его реализаций, или приложения Eclipse RCP, в котором разработчик расширяет один из классов Editor или View.
Фреймворк-ориентированная архитектура ограничивает свободу разработчиков, предписывая им что и как следует делать. Но, в итоге, исчезают повторяющиеся участки кода (boilerplate code), и разработчикам приходится (хотелось бы в это верить) тщательно следовать шаблонам проектирования.
Для Java существует множество фреймворков. Тем не менее, команда Android решила создать свой собственный. Возможно, одной из причин, по которой они так поступили, была необходимость поддерживать уникальную систему управления памятью.
В «обычной» Java объекты находятся в памяти до тех пор, пока сборщик мусора не доберётся до них. Происходит это только тогда, когда на объект нет ни одной ссылки от «живых» объектов (подробнее можно почитать здесь). В Android это не так. Если некий интерфейс пользователя скрывается (то есть он более не видим на экране), то нет никакой гарантии, что он находится в памяти, даже есть приложение в дальнейшем собирается использовать его. Если у ОС Android есть достаточно свободной памяти, эти объекты могут храниться в ней, но сборщик мусора может уничтожить их в любой момент, когда ОС решит, что памяти осталось слишком мало. То же верно и для процессов. Процесс, который в данный момент времени не показывает пользователю никакого графического интерфейса, может быть уничтожен ОС Android на абсолютно законных основаниях (есть одно исключение из этого правила — сервисы; об этом мы поговорим позже).
Рассмотрим пример. Пусть наше приложение имеет экраны A и B. Пользователь сначала открывает экран A, а затем экран B; с этого момента экран A стал невидим. Это означает, что экран A и вся логика, содержащаяся в нём, может находиться в памяти, а может и не находиться. Так, нет гарантий, что объекты, связанные с экраном A находятся в памяти, пока виден экран B. Логика экрана B не должна завязываться на нахождение объектов экрана A в памяти. Побочный эффект состоит в том, что архитектура Android принуждает к использованию архитектурного стиля стиля «shared nothing». Это означает, что разные части Android приложения могут вызывать друг друга и взаимодействовать между собой только формально; ни один из них не может обратиться к другому напрямую.
Хорошо, а что случится, если пользователь решит вернуться на экран A? Наверное, он захочет увидеть его в том же состоянии, в котором он оставил его, верно? Вот как фреймворк Android решает эту проблему: для каждого состояния жизненного цикла существуют методы, каждый из которых может быть переопределён разработчиком. Эти методы вызываются фреймворком в заранее определённые ключевые моменты, например, когда пользовательский интерфейс показывается на экране, прячется и т.п. В этих методах разработчик может реализовать логику для хранения и восстановления состояния объектов.
Подобная обработка скрытия пользовательских интерфейсов и существование кнопки «назад» на Android-устройствах приводит к необходимости наличия стека пользовательских интерфейсов, в котором текущий видимый интерфейс помещается на вершину, а все остальные сдвигаются вниз (стековая операция «push»). Нажатие «назад» удаляет интерфейс с вершины стека и показывает элемент, который был за ним (стековая операция «pop»). Подобный стек существует в Android. В документации он называется «activity stack» или иногда «back stack».
В плане обработки взаимодействия между пользовательским интерфейсом и его логикой Android следует архитектурному шаблону «Model-View-ViewModel» (MVVM). Для разработчиков это хорошая новость, поскольку MVVM — самая лучшая архитектура GUI-приложений на настоящий момент.
Архитектура MVVM была создана с целью разделения труда дизайнера и программиста, которое невозможно, когда Java-разработчик пытается построить GUI в Swing или разработчик на Visual C++ пытается создать пользовательский интерфейс в MFC. Разработчики — сообразительные парни и имеют множество навыков, но создание удобных и привлекательных интерфейсов требует абсолютно других талантов, нежели те, которыми они обладают разработчики. Эта работа больше подходит для дизайнеров интерфейсов. Хорошие дизайнеры интерфейсов лучше знают, чего хотя пользователи, нежели эксперты в области проектирования и написания кода. Понятно, будет лучше, если дизайнер интерфейсов создаст интерфейс, а разработчик напишет код, который реализует логику этого интерфейса, но технологии типа Swing или MFC просто-напросто не позволяют поступать таким образом.
Архитектура MVVM решает эту проблему ясным разделением ответственности:
- Разработка пользовательского интерфейса совершается дизайнером интерфейсов с помощью технологии, более или менее естественной для такой работы (XML)
- Логика пользовательского интерфейса реализуется разработчиком как компонент ViewModel
- Функциональные связи между пользовательским интерфейсом и ViewModel реализуются через биндинги (bindings), которые, по сути, являются правилами типа «если кнопка A была нажата, должен быть вызван метод onButtonAClick() из ViewModel». Биндинги могут быть написаны в коде или определены декларативным путём (Android использует оба типа).
Архитектура MVVM используется в том или ином виде всеми современными технологиями, например Microsoft WPF и Silverlight, Oracle JavaFX, Adobe Flex, AJAX.
Мы упоминали, что различные части Android-приложения могут вызывать друг друга и взаимодействовать между собой только формально. Как же это достигается? Фреймворк Android использует несколько шаблонов взаимодействия:
- Обмен сообщениями с помощью класса Intent
- Наблюдатель с использованием классов Intent и BroadcastReceiver
- Позднее связывание с последующим вызовом метода используется для доступа к контент-провайдерам (ContentProviders) и локальным (внурипроцессным) сервисам (Services)
- Позднее связывание и межпроцессное взаимодейтсвие (Inter-process Procedure Communication, IPC) для вызова сервисов (AIDL)
Не волнуйтесь, если что-то из этого звучит непонятно. Подробные объяснения будут в следующих статьях.
Источник