Adaptive icon android studio

Адаптивные значки

В Android 8.0 Oreo появилась поддержка адаптивных значков.

Для работы с адаптивными значками следует использовать API 26 и выше. Адаптивные значки состоят из двух слоёв: фон и основная часть.

В манифесте по-прежнему остаётся старая запись о значке.

Далее следует создать файл res/mipmap-anydpi-v26/ic_launcher.xml. Android Studio 3.0 генерирует подобный файл, можете изучать его.

Слои содержат векторные изображения VectorDrawable. К слову сказать, в качестве фона можно использовать просто цвет.

Для передней части значка можно использовать PNG-файл (используйте ресурсы mipmap).

Для совместимости с Android 7 вы должны также создать ещё один файл ic_launcher_round.xml с таким же содержанием.

Если изучить ресурс для фона, то можно заметить, что для значка используются размеры 108dp*108dp. Основной слой значка имеет те же размеры, но нужно учитывать одно обстоятельство — фоновый слой работает как маска, накладываемая на передний значок. Поэтому вы должны проследить, чтобы маска случайно не закрыла важные детали значка.

Гарантировано будет виден центр значка 66dp, а 77dp применимо к общему размеру значка.

Адаптивные значки можно применить к App Shortcut.

На эмуляторе следует выбрать устройство Pixel и включить у него режим разработчика. Далее в настройках домашнего экрана появится пункт Change icons shape.

Дополнительное чтение

Implementing Adaptive Icons – Google Developers – Medium — в статье приводится пример применения линейного градиента для тени.

Releases · nickbutcher/AdaptiveIconPlayground — приложение с открытым исходным кодом для удобного просмотра эффектов значков с настройками.

Источник

Implementing Adaptive Icons

Android O introduces an new application icon format called adaptive icons, intended to make all icons on a device more coherent. This post will look into how to build adaptive icons for your app. It’s unlikely that many apps will be minSdkVersion 26 any time soon, so this post will also examine techniques for adding this additional icon as efficiently as possible.

It’s also worth pointing out that Android Studio 3.0 includes a new wizard to help you to create adaptive icons which we won’t cover here; we’ll stick to the fundamental format and techniques.

If you’re interested in the back story of this format or how to design an adaptive icon the check out these posts:

Understanding Android Adaptive Icons

Android O introduces a new format for app icons called adaptive icons. To better understand the motivation and…

Designing Adaptive Icons

Android O introduces a new app icon format: adaptive icons. Adaptive icons can make devices more coherent by unifying…

Basics

Adaptive icons are a new drawable type, namely AdaptiveIconDrawable . You’ll likely never need to work with the class directly, but to define it in XML and point to it from your manifest. You can do so using this format:

Each drawable must be 108dp*108dp in size; background drawables must be opaque whilst foregrounds can contain transparency.

You also need to build your apk with buildToolsVersion 26.0.0 or higher.

Actually minSDK is 26

Because adaptive icons are only used on API 26+, you can rely on certain features being available to you. Specifically pretty capable VectorDrawable support.

Unfortunately you can’t use custom drawable inflation; as your icon will be loaded by other apps’ processes, you need to stick to platform drawable types.

Utilizing vectors is attractive as it allows us to specify the drawable once in a very compact format. That means it will be crisp at every density without bloating your APK.

Читайте также:  Iris and the giant android

In particular, many developers do not seem to have taken advantage of VectorDrawable ‘s support for gradients. On this topic, I’d recommend reading Ian Lake’s recent post on implementing an adaptive icon which covers the basics.

VectorDrawable Adaptive Icons

With Android O finalized as API 26, now’s the time to start thinking about adding an adaptive icon without the bloat of…

Ian shows how to use a simple linear gradient, but VectorDrawable has a few more nifty tricks. Here’s an example of implementing a ‘long-shadow’ using a radial gradient with multiple color stops. I’m also using the inline resource syntax which lets you embed what would be multiple files into a single file (via AAPT tricks, commonly used with AnimatedVectorDrawable s):

Most icons include some kind of drop-shadow element in them (per the material guidelines) which unfortunately VectorDrawable does not support. With adaptive icons, there are two features that make vectors more relevant:

  1. The launcher is now responsible for masking the overall drawable and providing any drop shadow for the full shape. You no longer have to bake in a shadow for the entire shape.
  2. The icon is comprised of a background and a foreground image, so if one of those layers does not require any shadows, then it can take advantage of vectors.

Some simple shadows can be approximated using gradients but unfortunately not everything.

Minimum viable raster

If you can’t implement your design with vectors then it’s perfectly fine to do so using PNGs. Your launcher icon is such a crucial asset that it’s definitely worth a few extra bytes to make the right impression.

There is however a neat trick that you can utilize for assets with areas of transparency in them… which is somewhat common in adaptive icon foregrounds. While this kind of asset likely compresses well at build time, at run time each pixel takes up 8 bits of memory no matter what the opacity. To minimize this, if the transparency is around the edges, you can trim these areas from the PNG and use an InsetDrawable to wrap it and fill it out to its 108dp size. Now unfortunately InsetDrawable doesn’t love being resized (i.e. if you set a top inset of 16dp it will always be 16dp no matter how the drawable’s bounds are resized) so in API26 fractional insets were added to mitigate this. This lets you specify insets as a percentage of the overall drawable so they will scale correctly.

For example, say you have a foreground asset which is 54dp*54dp; instead of placing that in a 108dp*108dp asset amidst transparency you can do the following.

Here’s an example using this technique where we remove the top/left portion of the asset which would otherwise contain transparency and instead inset a trimmed version:

Note that you’ll still have to provide the trimmed raster asset at different densities, but at least each will be smaller and in-memory size will be much reduced.

Take a shortcut

Adaptive icons aren’t solely for app icons, they’re also used for app shortcuts. App shortcuts can be pinned to the homescreen so they need to fit in with app icons. The (pre-O) design specs call for shortcut icons to sit on a grey circular background. In Android-O, the background should fill the adaptive icon mask. If you don’t update to adaptive, your shortcut icon will be scaled down and placed on a white background.

To implement this in my app Plaid, I initially added new icons in the v26 configuration, re-drawn for the adaptive grid and keylines. I wasn’t happy with this approach as they were essentially scaled versions of the v25 icons; meaning I now had two icons to maintain. Ultimately I decided to break the v25 icon into a foreground (e.g. the search icon) and background (the grey circle) and combine them with a LayerDrawable :

Читайте также:  Provisions android что это такое

I could then use the same foreground asset in the adaptive icon. On v25, app shortcut icons are 24dp within a 48dp asset; on v26 they’re 44dp within a 108dp asset:

To use the same 48dp file I needed to inset it so that the icon is the correct size once it’s scaled up (yay vectors!) to the 108dp adaptive icon size. The background is achieved using a ColorDrawable :

AdaptiveIconDrawable will scale the supplied asset to 108dp, so to calculate the inset required to produce a 44dp icon: 48 / 24 * 44 = 88; that is we need to inset the scaled up asset by 10dp each side: 10 / 108 → 9.26%

Play around

If you’re building an adaptive icon, then the Adaptive Icon Playground app might be useful to you. It lets you preview adaptive icons on your device, see how they look with different masks applied and explore some motion effects.

You can grab an APK (for devices already running Android-O) or check it out on github:

Источник

Android Adaptive Icons

Deliver an eye-catching first impression by making your Android icon pop

  • Jimmy Morales, Senior Developer, Guatemala

Adaptive icons are definitely not a new thing in the Android world. They were introduced in Android 8.0 (Oreo), around four years ago. Not so many things have changed since then, but I think it will be good if we do a quick review on the topic.

Legacy Icons

Let’s talk about how icons were implemented in versions prior to Oreo, which we will call legacy icons from now on. Legacy icons are easy to implement. You need to have at least one PNG for each different density from mdpi to xxhdpi (four in total), but ideally you should also add one for the xxxhdpi. The icon’s size needs to be 48×48 dp and it can have any transparency. This opens the opportunity to have icons with different types of shapes. It means your icon can be a circle, square, or any shape really.

Initially having a unique shape was a good practice because it meant your app icon was more likely going to stand out compared to other apps. But this resulted in a Launcher full of icons with different shapes and sizes and a lot of inconsistency.

Normalizing icon shapes and sizes

This started a new movement on trying to normalize the icons shapes and sizes in the Android Platform. Samsung was the first OEM that introduced a background behind the icons that make them look more consistent.

Left: Standard icon look. Right: Icons with backgrounds. Source: cnet.com

The second attempt at trying to introduce a more consistent icon experience was in Android 7.1 (Nougat) with the introduction of the roundIcon . This new feature had some restrictions, especially with OEMs looking to differentiate their devices by having different icon shapes (ie: Pixel devices use circular icons, Samsung a rounded square shape, other OEMs might use a rectangular shape). This was solved in Android 8.0 with the introduction of Adaptive Icons.

So… Adaptive Icons

An Adaptive Icon is made up of two layers, a foreground and background, both of 108×108 dp. Ideally these two layers should be vector assets, but they can also be PNGs. The downside of using PNGs is that you will need to provide at least 4 different PNGs per each density (mdpi to xxhdpi) for each layer (8 PNGs in total). With vector assets you will only need two files which will save you a lot of space.

Basically, Android will apply a mask to both layers and clip an area around your icon. Different OEMs will apply different shapes of masks. You need to have in mind that because of the applied mask you will need to put your icon in a safe area that is around 33dp from the center of the icon.

Читайте также:  Драйвер wifi адаптера для андроид

How to create an Adaptive Icon?

If you are a developer (with no design skills like myself) the short answer is to use the Asset Studio from Android Studio. Using Asset Studio is very easy, you can import both of your layers and the Asset Studio will generate the files for you.

The Asset Studio will show you the safe zone and a really nice preview on how different masks will be applied to your icon. You can resize both of the layers if needed. The background layer can be just a color drawable, but as I mentioned before you can also provide a vector asset, that means the background can be really anything, for example, you can have a gradient as the background layer.

When creating the Adaptive Icon, Asset Studio will generate for you several files. It will add the two layers as drawables, for example, if you used vector assets for your layers it will generate a drawable/ic_launcher_foreground.xml for your foreground layer and a drawable/ic_launcher_background.xml for your background layer.

The Adaptive Icon file by default will be called ic_launcher.xml . If your app’s minimum SDK is 26 or higher this file can live in the mipmap resource directory, but if not (most of the apps), it will be stored in the mipmap-anydpi-v26 resource directory. This is because Adaptive Icons are only supported on API level 26 or higher, and on versions below 26 you will need to have the legacy icon saved in the mipmap-mdpi , mipmap-hdpi , etc.

For example, if your minimum SDK is 23 you could end up with this file tree in your res directory:

If the ic_launcher_round adaptive icon is the same one as the normal ic_launcher , instead of duplicating the file you can provide a resource alias in your values-anydpi-v26 folder.

Now you only need to specify the icon file in your app’s AndroidManifest.xml like you would normally do.

And this is how the Adaptive Icon looks internally. It is pretty simple, you only need to use the adaptive-icon tag and inside add both layers using the background and foreground tags (Asset Studio does this for you).

For designers

If you are a designer and like to use fancy design tools, you can also use these tools to design Adaptive Icons.

More Adaptive Icon stuff.

The real reason for having two layers is because it allows OEMs to do really cool animations when an user interacts with your icon, like moving the foreground layer on top of the background layer.

But, how can we test the animated visual effects of our Adaptive Icons in a real device? Well, thanks to Nick Butcher again, we can use his Adaptive Icon Playground app to see how the animated visual effects perform in the icon. You can download the APK from the repo, run the app and you will be able to see the Adaptive Icons of all of your installed apps in your device.

Wrapping up

Implementing Adaptive Icons is a great way to make your app follow the best practices and is in tune with the other apps on the devices of our users. Remember that App Icons are a great investment because they usually are the first thing the user sees, and that also involves seeing the animated visual effects in the latest Android versions or supporting different Icon shapes in different OEMs.

At the time of writing this article, Android 12 is in beta, but hopefully when it gets stable in the next month I’ll update the article if we get something new.

Special thanks to Chris Weathers, Camilo and Mauricio for reviewing this.

Источник

Оцените статью