Android toolbar add icon

Adding Icons and Menu Items to an Android Toolbar

You now need to add some icons to the toolbar you added in the previous lesson. There’s also a thing called the Overflow Menu. This is for items that won’t fit on the toolbar. You’ll then typically see three dots. Press the dots and you see a sub menu appear. This sub menu is the Overflow Menu. Let’s see how to do that.

Items that go on your toolbars come from a separate XML file that is placed in a menu folder. You then attach the XML file to your toolbar using Java code.

First, we’ll need the menu folder.

In the Explorer area on the left of Android Studio, right-click the res folder. From the menu that appears, select New > Android resource directory:

When you get the dialogue box up, select menu from the Resources type dropdown:

The Directory name box at the top will then change to menu:

Click OK to create a menu folder inside of your res directory:

Now right click your new menu folder. From the menu that appears, select New > Menu resource file:

When you get the New Resource File dialogue box up, type menu_items as the file name:

Click OK to create a new XML file in your menu folder:

The XML file will open up in Design view in your main coding area. It should look something like this: (Later versions of Android Studio will have a Cast Button item at the top.)

Have a look on the left, though, and notice the Palette and the Component Tree. You can drag items from the Palette onto either your Component Tree or directly onto your toolbar.

Читайте также:  Увеличить громкость звука наушников андроид

Drag a Menu Item from the Palette to your Component Tree or toolbar:

Your Component Tree will then look like this:

And your layout will look like this:

Notice that the layout is showing the three dots for the Overflow Menu, and a menu item with the default name of item.

With your new menu item selected, have a look at the properties area on the right:

We’ll need IDs for the menu items. Type favourites_page as the ID. For the title, click the Pick a Resource button to the right of the title area. Then select the favourites string resource you set up in the previous lesson:

Click OK and your layout will update with your new title:

The title will appear only if a menu item is pushed to the Overflow Menu. It is pushed to the Overflow Menu if there is not enough room on the toolbar. But only if you have specified this in the showAsAction property. Click inside of this property to see the following box appear in earlier versions of Android Studio:

In later versions, you need to click the little flag. You’ll then see the same dialog box but in a different design:

Select the one for ifRoom. This means that the item will appear on the toolbar if there is room for it, otherwise it will get pushed to the Overflow Menu. The never means that it will never appear on the toolbar but always on the Overflow Menu; always means it will always appear on the toolbar; withText means that the title you add will always be displayed. (The collpaseActionView item is used with something called an Action Layout. We won’t be using these.)

Your properties area should look like this, so far:

You’ll probably want an icon to appear for your toolbar items. Instead of designing one yourself, there are lots of inbuilt ones you can use. You add these to the drawable folder as a Vector asset. You’ll learn how to do that in the next lesson below.

Читайте также:  Космические корабли тесла шаттл союз андроид

Источник

Material Design. Динамический Toolbar на живом примере

Уверен, что те, кто следят за изменениями в мире Android, заметили, что Toolbar начинает играть в приложениях всё более значимую роль. Например в последней версии Gmail клиента в Toolbar вынесен почти весь функционал по работе с почтой, а в новом Google Chrome Toolbar отвечает за работу с текстом страниц.

В данной статье я постараюсь рассказать о создании динамического Toolbar, который позволит пользователю работать с контентом четырьмя различными способами в рамках одного Activity. Мы рассмотрим весь процесс разработки Toolbar-a начиная с xml файлов стилей и заканчивая анимацией иконок, а в конце статьи я оставлю ссылку на GitHub репозиторий с примером полностью рабочего приложения.

Начнём с постановки задачи

Мы будем разрабатывать Toolbar для приложения, которое позволит пользователю следить за изменениями цен на акции. На главном экране будет расположен список всех акций, за которыми следит пользователь, мы также должны реализовать базовый функционал: удаление, поиск и сортировку акций. Вот так я реализовал этот функционал с помощью динамического Toolbar-a:

Стандартный режим Режим поиска Режим удаления Режим сортировки

Создаём xml файлы конфигураций

Итак, в первую очередь нам нужно создать xml файл самого Toolbar-a. Я советую сделать это в отдельном файле, так как в будущем мы скорее всего захотим использовать один и тот же (или похожий) Toolbar во всех Activity нашего приложения.

Теперь мы можем добавить toolbar.xml в xml Activity следующим образом:
res/layout/activity_main.xml

Поскольку в нашем Toolbar будет располагаться виджет поиска, мы можем настроить его внешний в вид в файле styles.xml нашего приложения. В 21 версии Android SDK появилось гораздо больше возможностей для кастомизации виджета поиска (SearchView Widget), вы можете посмотреть полный список атрибутов по этой ссылке: AppCompat v21 — Material Design for Pre-Lollipop Devices! В этом же файле мы зададим цвет нашего Toolbar.

И наконец создадим файл со списком всех элементов нашего Toolbar-а. Тут у нас есть несколько вариантов:

  • В начале создать только те элементы, которые будут видны в стандартном режиме, а затем в коде добавлять или удалять элементы при переходе между режимами.
  • Сразу создать все существующие элементы в xml файле, а в коде просто управлять их видимостью.
Читайте также:  Прошивка s6802 android 4

Я выбрал второй вариант так как у нас не так много элементов внутри Toolbar и нам нет смысла экономить память храня в ней только видимые элементы.

Также существует два способа создания элементов Toolbar:

    Создавать элементы внутри меню (Menu), как экземпляры класса MenuItem. Этот способ использовался в предыдущих версиях Анрдроид (API Level

Источник

How to Create Custom AppBar/ActionBar/ToolBar in Android Studio | Java

Today in this tutorial, we’re going to see how to create a custom AppBar/ActionBar/ToolBar in android.

I also already created a tutorial on this topic, but here I will demonstrate it with different examples.

Gradle dependency

for circle image view:

Set the styles

now go to your styles.xml file and set the theme to NoAction Bar so that we can create our own toolbar.

Design our AppBar/ActionBar/ToolBar

now go to your main XML file and create a ToolBar and set the width and height, make sure min-height should be actionBar size.

this will give you just a toolbar without any field. Look at the below image.

for the logo, we’re using a circular image view. Already add the dependency. Put it inside the toolbar and do the adjustment.

here we set our title to null, so in the main java file assign our toolbar and do the below change

the result will be:

we can also set the logo by using app:logo=”your logo here” in your toolbar

the result will be:

for the menu, create a menu android resource folder and create a menu resource file ( /res/menu/custom_menu.xml)

import that menu in our main java file by using these code of lines

for adding a title simply add a textView inside the toolbar.

Источник

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