Custom menu icon android

Creating custom menu in android (Part-2/3 : The Action Bar)

Jul 4, 2017 · 4 min read

Continuing from the Part 1 of this tutorial which shows how make a custom menu in android, we will see how to design and integrate a toolbar (Action bar) in the project.

Let’s see how our toolbar looks :

We have only two components in the ToolBar

  • An ImageView for the hamburger menu icon
  • A TextView for the title

But by default the android studio provides us a ActionBar. So let’s remove it. for that go to values > styles.xml and change the AppTheme parent to NoActionbar:

now let’s design the toolbar

So the l ayout is pretty straight. A RelativeLayout with Icon on left and a title in the centre. We put the Relative inside a AppBarLayout. So the layout looks like this :

The BaseActivity — For consistent toolbar and menu across the app

We’ll create a BaseActivity which will extend AppCompatActivity. So in our other Activities, instead of extending AppCompatActivity, we will extend this BaseActivity. Why? Because we are already extending AppCompatActivity in BaseActivity as well as we will be add some custom functionality in it. So extending our BaseActivity, all other activities can access all those functionalities.

So in BaseActivity, we will add the toolbar we just designed and add the code for the hamburger menu click events.
Let’s see how it is made. Create an empty activity BaseActivity which will create an activity_base.xml for layout:

In the layout file, we’ll add the toolbar that we designed and below that we’ll leave empty space for the rest of the screen. So when we extend this BaseActivity, the other screens will get this toolbar on top and the corresponding xml design below it in empty space.
So the code looks like :

The above written code results in a structure which looks like this:

Now we will initialize the icon and toolbar in BaseActivity.java and write a method where the empty space will be covered by the screen specific designs.
So our complete BaseActivity.java code looks like

Extending the BaseActivity and adding our design to it.

Lets say we have a MainActivity and we are extending BaseActivity in it. we will also see how to show the activity_main.xml design in it.

Let’s break the above written code.
Remember we had empty space in activity_base.xml. In this empty space we will add the activity_main.xml

We have a function names initAddLayout already in the BaseActivity.java.

Then we took reference of the TextView and ImageView of the toolbar

Now once we have the reference, we can use them as we want. So we changed the label and the menu button click event according to every activity

Summary

So, now we have a MainActivity which extends our BaseActivity, so it has the common toolbar and the rest of the content of the screen is also added. So in all the Activities, we’ll have our BaseActivity extended so we get a common toolbar.

So assume you need a toolbar with some icons and fixed events on those icons on some 20 screens of your app. You need not to create a menu xml and define the events in onMenuItemSelected in all 20 activities. Instead, you simply design a toolbar, include it the BaseActivity, write the functionality only once in the BaseActivity and extend this BaseActivity in every other Activity

Источник

Кастомные view для пунктов меню в приложении андроид

В этом уроке вы узнаете, как создавать интерактивные значки для пунктов меню, отображаемых в тулбаре android-приложения.

Читайте также:  Мегого для андроид приставки

Android framework делает многое, чтобы помочь нам создать и взаимодействовать с элементами меню действий (это маленькие значки на правой стороне панели инструментов). Путем вызова нескольких методов установки framework будет автоматически обрабатывать три вещи для нас.

  1. Вставка view в панели инструментов, обеспечивая правильное размещение, размер изображения и пространство между соседями
  2. Добавление слушателя нажатия view
  3. Определение визуальной обратной связи при щелчке (например, изменение цвета фона или пульсации)

Все, что остается сделать — определить текст заголовка и значок drawable в нашем файле макета меню, инфлейтить этот макет в onCreateOptionsMenu() и обрабатывать щелчки в onOptionsItemSelected(). Если вы когда-либо работали с пунктами меню — для вас здесь нет ничего нового. Если не работали — смотрите этот урок.

Разметка пункта меню:

Реализация в коде активити:

Вот так это выглядит:

Но зачем мы хотим использовать кастомную view, а не просто иконку? Допустим, у нас есть представление, которое отображает количество предупреждений, полученных в нашем приложении. Нам нужно обновить значок, чтобы показать или скрыть красный круг с числом внутри. Допустим, что наш пункт меню «Обновить» инициирует вызов для выборки последнего числа оповещений и обновляет элемент оповещения меню. Наше окончательное решение будет выглядеть следующим образом:

Первое, что приходит в голову — динамично менять картинку drawable, используемую в пункте меню. Мы можем схитрить и просто подставлять 11 различных символов drawables для нашего приложения в цикле:

  • icon with no red circle
  • icon with empty red circle
  • icon with red circle and «1»
  • icon with red circle and «2»
  • icon with red circle and «9»

Это могло бы быть проще для нас как разработчиков (но больше работы для нашего дизайнера), но дополнительные ресурсы начнут раздувать размер нашего apk. Вместо этого мы можем использовать кастомные view, чтобы достигнуть того же самого эффекта с меньшим количеством ресурсов.

Определение Custom View

Ключевым моментом для кастомного view является использование app:actionLayout вместо android:icon в нашем файле ресурсов меню.

Далее мы сделаем макет кастомного view в папке layouts.

Теперь у нас есть красный круг — FrameLayout, который содержит TextView нашего счетчика оповещения . Мы также имеем ImageView нашего значка предупреждения. Наконец, мы должны обернуть все в корневой FrameLayout. Еще нам необходимо жестко закодировать размер нашего значка согласно правил материального дизайна . Мы определяем размеры иконки в файле dimens.xml.

Если мы запустим приложение, мы увидим новый значок, но возникают две проблемы:

  1. onOptionsItemSelected не вызывается при нажатии на кастомный пункт меню
  2. Значок визуально не реагирует на клики (т. е. нет пульсаций)

Мы исправим эти проблемы через минуту, но сначала давайте напишем код, чтобы получить значок, отображающий количество оповещений при запросе.

Использование Custom View

Мы хотим настраивать кастомное view в нашем меню при каждом отображении. Таким образом, вместо настройки его в onCreateOptionsMenu, мы будем делать некоторую работу внутри onPrepareOptionsMenu. Так как наш пункт меню — просто заполненный макет, мы можем работать с ним как с любым макетом. Например, мы можем найти view id.

Мы получаем доступ к корневому view-элементу этого пункта меню, находим сначала пункт меню, а затем вызываем getActionView. Теперь мы сможем найти красный круг и счетчик оповещений в поле textview.

Затем мы обновляем значок оповещения, когда пользователь нажимает на кнопку «обновить» пункта меню:

У нас теперь есть обновление пункта меню:

Фиксим траблы

Как я сказал прежде, у нас еще есть две проблемы:

  1. onOptionsItemSelected не вызывается при нажатии на кастомный пункт меню
  2. Значок визуально не реагирует на клики (т. е. нет пульсаций)

Давайте сначала займемся первой. По некоторым причинам, когда наш пункт меню зависит от app:actionLayout вместо android:icon , onOptionsItemSelected не будет вызываться для кастомного элемента меню. это известная проблема. Решение – просто добавить наш собственный слушатель ClickListener корневому view и вручную вызвать onOptionsItemSelected. Будем также сбрасывать счетчик предупреждений, когда пользователь щелкает пункт оповещения в меню:

Теперь если вы запустите приложение, то обнаружите, что нужно нажать значок предупреждения несколько раз, прежде чем он отреагирует. Выберем «Показать границы макета» в параметрах разработчика и сразу же увидим проблему:

Наша кастомная вьюшка меню не получает автоматически отступ, как у обычных пунктов меню. Поэтому площадь нажатия значка значительно уменьшается. Мы можем исправить это, обернув наш view в еще один FrameLayout :

Возвращаясь к рекомендациям по Материальному дизайну, мы должны установить новые размеры для корневого view 48dp высоты и ширины.

Это успешно увеличивает нашу область щелчка.

Последнее, что нам нужно сделать, это включить визуальную обратную связь при выборе пункта меню. Для Lollipop+ устройства это означает рябь; для более старых устройств это означает изменение цвета фона.К счастью для нас, эта функциональность уже содержится в attr/selectableItemBackgroundBorderless . Поэтому все, что нам нужно это новое view в нашем файле макета, которому мы можем задать этот атрибут:

Читайте также:  Наруто ураганные хроники для андроида

Идеально. Все выглядит хорошо. Пульсация хорошо смотрится на нашем устройстве Android 22 и изменение цвета фона выглядит хорошо на нашем устройстве Android 19.

API 19 device API 22 device

Последний штрих

Прежде чем мы можем закончить этот код, обратите внимание, что это не совсем хорошо работает на устройствах API 23+. Границы ряби на нашем пункте меню гораздо больше, чем на стандартном меню:

Ripple границы на стандартном меню Ripple границы кастомного меню

Чтобы исправить это, нам нужно сделать несколько проб и ошибок, чтобы выяснить, правильный размер границы ряби. Мы его будем предоставлять для API 23+ устройств. Наконец, мы будем обновлять макет, чтобы использовать этот новый размер (вместо того, чтобы просто установить свойство match_parent для ripple view). Вы можете проверить самостоятельно, но на API 23+ Эта ряби граница должна быть 28dp.

Источник

How to make a custom icon for Android

Source: Ara Wagoner / Android Central

Icon packs have holes. Icon packs don’t always fit your wallpaper. And when you’re theming your phone, maybe what you need isn’t in an icon pack at all. That’s OK. We don’t need no stinkin’ icon packs, especially in 2020 when apps like Icon Pack Studio exist. We can edit together our own custom icons! It’s easy. All you need is some kind of photo editor — be it the latest Photoshop or free cloud-based editors like Pixlr E — and a little creativity.

Finding your image

Most third-party launchers like Nova Launcher let you set any image you want as an app icon. With that kind of freedom, it can be a bit daunting finding inspiration for your icons. While most custom icons are theme-driven — using color palettes or pictures based on a wallpaper — here are some more ideas for custom icons or where to pull them:

Source: Android Central

  • Game elements: Inventory items in a lot of games, like these Dark Souls items, are easy to set as icons because most are designed to fit into a square and transparent PNG images of the items are easily found on fan sites and game wikis.
  • Emoji: Emoji are already square images that are mobile friendly and can be decoded a million different ways. You can disguise apps by how they make you feel, what they remind you of, like a secret code only you can decipher.
  • Music: If you want to show off your intense love of your favorite group or band, make their already-square album covers into custom icons. ABBA’s SOS for the dialer? Metallica for Chrome? Can You Feel The Love Tonight for Tindr?
  • Logos: Sports teams, name brands, heck even a lot of movies and bands have their logos online in transparent PNG images, ready to be set as a custom icon. If you’re a sports fan, your team’s logo is the easiest app drawer icon in the theming world, and in most cases it won’t need any editing at all.
  • Vector sites: Want an emblem for a globe, or a lilypad, or bell bottoms? Icon sites and vector repositories are treasure troves of icon fodder, and once you download them, you can gussy them up with textures and color palettes. Flaticon has a fantastic selection of both free and paid icons.

If the image you find is a transparent and square image, congratulations! You can apply it as-is. If it isn’t, there’s a few edits you may need to make.

Editing: How to turn an image into an icon

Let’s get one thing out of the way right away: you do not to pay for Photoshop just to make custom icons. You can absolutely use free photo editors, like Pixlr E and remove.bg to get the job done for free, and you can use them on your phone if you don’t have a laptop handy.

Here’s what can be wrong with an image and how to fix it:

Source: Android Central

    If your source image doesn’t have a transparent background, you need to delete the background if you want to apply it on Android (or add a color palette background on iOS), you can use Photoshop, Pixlr E, or remove.bg to get rid of it and save it as a transparent PNG.
Читайте также:  Фон для автомагнитолы андроид

If your source image isn’t a square image, you need to pad out the image and make it a square. You can do this in Photoshop or Pixlr E using the Image > Canvas size option and then expanding the canvas out into a square.

Source: Android Central

  • If an image is too large — if it looks too jagged or busy — you can can resize it using Pixlr E, Photoshop, or even the built-in Gallery app in Chrome OS or Windows to resize the image to a smaller size. 500x50px is a good size for icons, as it allows them to look good even when screen zoom is turned up, but it’s not so big that details will look janky.
  • Icon Pack Studio: Build your own icons seamlessly

    Source: Android Central

    If you’re not interested in hunting down a new image for every single app on your home screen — to say nothing of all the apps in your app drawer — then let me share what I use for my home screen icons these days: Icon Pack Studio. This app doesn’t make standalone icons, it creates a custom icon mask that it can then apply to every single app in most third-party launchers, though it’s most seamless on Smart Launcher 5 since it’s made by the Smart Launcher team.

    You can choose the background shape, how big and what kind of app icon is used, and then add stroke, textures, gradients, and other fun effects to the mask before exporting it (for other launchers) or directly applying it (on Smart Launcher 5). You can set colors by hex code, allowing for the icon to be perfectly matched to your wallpaper or widgets.

    Make it your own

    Icon Pack Studio

    Pick your background, pick your textures, and bam, instant gapless icon pack! This could replace all your custom icon and icon pack needs.

    Applying a custom icon

    The method for applying a custom icon can vary a little depending on the launcher you use. Here are the processes for applying a custom icon on the most popular launchers, and how to apply a custom icon even if your launcher doesn’t support custom icons itself.

    Nova Launcher

    1. Long-press the shortcut you wish to change.
    2. Tap Edit.

    Tap the icon box to edit the icon.

    Source: Android Central

    Navigate to and select your custom icon.

    Source: Android Central

    Enjoy your new icon

    Source: Android Central

    Action Launcher

    1. Long-press and hold the app shortcut you’d like to edit.
    2. Drag the icon up to Edit.

    Swipe up the menu to reveal the list of sources for your icon.

    Source: Android Central

    Return to the home screen to enjoy your new icon.

    Source: Android Central

    The only limits for custom icons are your own tastes and your imagination! What custom icons have you used in a theme? Got a great idea for some custom icons but don’t quite know how you could pull it off? Leave your ideas in the comments below!

    We may earn a commission for purchases using our links. Learn more.

    Samsung needs to bring back its iPod competitor

    I don’t want to buy an iPod Touch. Since I want a reasonably priced PMP with acceptable audio hardware that can install a few crucial apps, I might have to.

    VoLTE: How to use it and why you should care

    VoLTE — or Voice over LTE — is the new standard for calling throughout the U.S., Canada, and parts of Europe. Not only does it facilitate much higher call quality between cell phones, but it allows devices to stay connected to LTE while on a call, improving data speeds for everyone.

    PlayStation reportedly planning service to compete with Xbox Game Pass

    Sony is planning to create a service similar to Xbox Game Pass, according to a new report. The service could launch as early as sometime in the spring of 2022, with multiple tiers.

    These Halloween-themed wallpapers are perfect for the season

    Old wallpapers are sad wallpapers. Get some warm, new, pumpkin-y varieties to celebrate the spooky, yet sweet season we call Halloween.

    Источник

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