- Material Design. Динамический Toolbar на живом примере
- Начнём с постановки задачи
- Создаём xml файлы конфигураций
- Toolbar with menu items android
- Adding Icons and Menu Items to an Android Toolbar
- Using the Android Toolbar (ActionBar) — Tutorial
- 1. Introduction to the toolbar
- 1.1. What is the toolbar (action bar)?
- 1.2. Action bar on devices lower than API 21
- 1.3. Once upon a time their was the options menu
- 2. Using the toolbar
- 2.1. Creating actions in the toolbar
- 2.2. Reacting to action selection
- 2.3. Search an action in the action bar
- 2.4. Changing the menu
- 2.5. Making the toolbar context sensitive with the contextual action mode
- 2.6. Contributing to the action bar with fragments
- 2.7. Changing the visibility of the toolbar bar
- 2.8. Assigning a Drawable
- 2.9. Dimming the navigation buttons
- 2.10. Using immersive full screen mode
- 2.11. Enabling the split toolbar
- 3. Exercise: Using the contextual action mode
- 3.1. Target
- 3.2. Create menu resource in the res/menu folder
- 4. Making the action bar dynamic
- 4.1. Custom views in the action bar
- 4.2. Action view
- 5. Action provider
- 5.1. What is an action provider?
- 5.2. Example: usage of the ShareActionProvider
- 6. Navigation via the application icon
- 6.1. Application icon as home
- 6.2. Application icon as Up button
- 7. Exercise: Using the toolbar
- 8. Exercise: Add a toolbar to your application
- 8.1. Add a refresh icon
- 8.2. Add menu resources
- 8.3. Turn off the default action bar from the styling
- 8.4. Add a toolbar view to your activity layout
- 8.5. Adjust your activity
- 8.6. Run the application and test the toolbar
- 8.7. Trigger an intent via the toolbar
- 9. Trigger a method in your fragments via the toolbar
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 файле, а в коде просто управлять их видимостью.
Я выбрал второй вариант так как у нас не так много элементов внутри Toolbar и нам нет смысла экономить память храня в ней только видимые элементы.
Также существует два способа создания элементов Toolbar:
- Создавать элементы внутри меню (Menu), как экземпляры класса MenuItem. Этот способ использовался в предыдущих версиях Анрдроид (API Level
Источник
Toolbar with menu items android
There are two kind of bar with control items in activity
- ActionBar is action control bar or navigation bar you usually see at the top of an app, it usually has an app logo icon on the left, name of the current screen next to the logo, and other menu list on the right. To use actionbar, you don’t have to define an actionbar in the layout file which is handy but it deosn’t give you much flexibilities when you want to do some customizations in the actionbar, such as adding background image, animations, place the actionbar on the bottom instead on the top.
- Toolbar does evertying you can do with ActionBar, and gives you the freedom to do customiztions that you can’t do easily with ActionBar .
You can use either old ActionBar (without any declarations in XML) or define android.support.v7.widget.Toolbar in activity layout and customize it look and events (more coding in this way).
Let’s look at ActionBar and it’s parameters. Insert following lines in onCreate method and you’ll get ActionBar with icon
ToolBar was introduced in Android Lollipop, API 21 release and is the successor of the ActionBar . It’s a ViewGroup that can be placed anywhere in your XML layouts. ToolBar ‘s appearance and behavior can be more easily customized than the ActionBar .
There are two ways to use Toolbar
- Use a Toolbar as an ActionBar when you want to use the existing ActionBar facilities (such as menu inflation and selection, ActionBarDrawerToggle, and so on) but want to have more control over its appearance.
- Use a standalone Toolbar when you want to use the pattern in your app for situations that an ActionBar would not support; for example, showing multiple toolbars on the screen, spanning only part of the width, and so on.
So, you should replace ActionBar with ToolBar if you want the flexibilities that comes with the Toolbar (adding background image, animations, place the actionbar on the bottom instead on the top and so on). Note that the ActionBar continues to work and if all you need is a static bar at the top that can host icons and a back button, then you can safely continue to use ActionBar .
To use Toolbar as an ActionBar , first ensure the AppCompat-v7 support library is added to your application build.gradle (Module:app) file
Second, let’s disable the theme-provided ActionBar . The easiest way is to have your theme extend from Theme.AppCompat.NoActionBar (or the light variant) within the res/styles.xml file
Now lets talk about the color scheme for our project, as you can see from the image below, there are attributes which you can set to get a basic color scheme of your App done, right now we are just dealing we App bar so we would talk about colorPrimary and colorPrimaryDark . colorPrimary as the name says is the primary color of your App and the App bar while with the colorPrimaryDark you can set the color of the status bar to a certain color.
Next, you need to add a Toolbar to your Activity layout file. Below I place the Toolbar at the top of a LinearLayout like the standard ActionBar
Next, in your Activity or Fragment , set the Toolbar to act as the ActionBar by calling the setSupportActionBar(Toolbar) method
Adding items to ActionBar or Toolbar
Menus are typically created in resource files using XML but they are stored in the res/menu directory though they can also be created in code. To create a menu resource, use the element.
The element defines each individual menu item and is enclosed in the element. A basic menu item looks as follows
The most common attributes are the following
- id , this is the standard resource identifier;
- title , this indicates the text to display;
- icon , this is a draw-able resource;
- showAsAction , this controls how the menu item is shown;
- enabled , this is enabled by default.
The showAsAction attribute controls how the menu item is shown. The options include the following:
- ifRoom , this menu item should be included in the Action Bar if there’s enough space;
- withText , this indicates that both the title and the icon should be shown;
- never , this indicates that the menu item should never be included in the Action Bar;
- always , this indicates that the menu item should be always included in the Action Bar.
First, we will add a string resource to the strings.xml file for the menu title. Start by opening the /res/values/strings.xml file and add the following element to the element EMail
Create a new file in the res/menu directory (right click on res — New — Android resource directory ) and call it menu_main.xml .
Open the menu_main.xml file and add the following XML to define the menu
With the menu now created, we just have to override the onCreateOptionsMenu() method in our activity to inflate the menu
Add the following method to the application to see a Toast when the EMail menu is selected
If you want to show icon in overflow menu use following snippet
Creating sub menus
Sub menus are created and accessed in almost exactly the same manner as other menu elements and can be placed in any of the provided menus, although they cannot be placed within other sub menus. To define a sub menu, include a element within an element.
Here is the XML form this recipe with two sub menu items added
Grouping menu items
Another menu feature that Android supports is grouping menu items. Android provides several methods for groups, including the following
- setGroupVisible() show or hide all items;
- setGroupEnabled() enable or disable all items;
- setGroupCheckable() set the checkable behavior.
Android will keep all grouped items with showAsAction=»ifRoom» together. This means all items in the group with showAsAction=»ifRoom» will be in the Action Bar or all items will be in the overflow.
To create a group, add the menu elements to a element. Here is an example using the menu XML from this recipe with two additional items in a group
A Toolbar is just a decorated ViewGroup and as a result, the title contained within can be completely customized by embedding a view within the Toolbar such as:
This means that you can style the TextView like any other. You can access the TextView inside your activity with:
Note that you must hide the default title using setDisplayShowTitleEnabled . This results in:
How to change color of menu in Toolbar
How to add back button to Toolbar
Android context menu example
First, define main activity layout
Second, describe context menu items
Third, define events and action in MainActivity class
onCreateContextMenu called when a context menu for the view is about to be shown. Unlike onCreateOptionsMenu , this will be called every time the context menu is about to be shown and should be populated for the view (or item inside the view for AdapterView subclasses, this can be found in the menuInfo ).
onContextItemSelected hook is called whenever an item in a context menu is selected. The default implementation simply returns false to have the normal processing happen. You can use this method for any items for which you would like to do processing without those other facilities.
Toolbar example in Kotlin
Following is MainActivity.kt file.
Following is activity_main.xml file.
Following is toolbar_menu.xml file.
Popup menu with icons example in Kotlin
Источник
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.
Источник
Using the Android Toolbar (ActionBar) — Tutorial
Using the toolbar in Android applications. This tutorial describes how to use the toolbar widget in your Android application. It is based on Android 6.0.
1. Introduction to the toolbar
1.1. What is the toolbar (action bar)?
The toolbar bar (formerly known as action bar) is represented as of Android 5.0 via the Toolbar view group. It can be freely positioined into your layout file. It can display the activity title, icon, actions which can be triggered, additional views and other interactive items. It can also be used for navigation in your application.
Before Android 5.0 the location of the toolbar (actionbar) was hard coded to the top of the activity. It is possible to disable the toolbar via the used theme, but the default Android themes have it enabled.
The following screenshot shows the toolbar of the Google+ Android application with interactive items and a navigation bar. On top it also indicates that the user can open a navigation bar on the side of the application.
1.2. Action bar on devices lower than API 21
The toolbar has been introduced in Android 5.0 (API 21). If you want to use the toolbar on devices with an earlier Android release you can use the downport provided by the appcompat-v7 support library. To use the toolbar on such devices add a compile dependency to com.android.support:appcompat to your Gradle build file. For example:
See the following link for setting up the library v7 in your project: http://developer.android.com/tools/support-library/setup.html.
1.3. Once upon a time their was the options menu
Applications with a target SDK version less than API 11 use the options menu, if such a button is present on the device. The option menu is displayed if the user presses the Option button. The toolbar bar is superior to the options menu, as the action bar is clearly visible, while the options menu is only shown on request. In case of the options menu, the user may not recognize that options are available in the application.
2. Using the toolbar
2.1. Creating actions in the toolbar
Entries in the toolbar are typically called actions. While it is possible to create entries in the action bar via code, it is typically defined in an XML resource file.
Each menu definition is contained in a separate file in the res/menu folder. The Android tooling automatically creates a reference to menu item entries in the R file, so that the menu resource can be accessed.
An activity adds entries to the action bar in its onCreateOptionsMenu() method.
The showAsAction attribute allows you to define how the action is displayed. For example, the ifRoom attribute defines that the action is only displayed in the action bar if there is sufficient screen space available.
The MenuInflator class allows to inflate actions defined in an XML file and adds them to the action bar. MenuInflator can get accessed via the getMenuInflator() method from your activity. The following example code demonstrates the creation of actions.
While you can define the actions also in your source code, it is good practice to do this via XML files, as this results in less boilerplate code. |
2.2. Reacting to action selection
If an action is selected, the onOptionsItemSelected() method in the corresponding activity is called. It receives the selected action as parameter. The usage of this method is demonstrated in the following code snippet.
2.3. Search an action in the action bar
To search for a menu item in a menu you can use the findItem() method of the Menu class. This method allows to search by id.
2.4. Changing the menu
The onCreateOptionsMenu() method is only called once. If you want to change the menu later, you have to call the invalidateOptionsMenu() method. Afterwards this onCreateOptionsMenu() method is called again.
2.5. Making the toolbar context sensitive with the contextual action mode
A contextual action mode activates a temporary toolbar that overlays the application toolbar for the duration of a particular sub-task.
The contextual action mode is typically activated by selecting an item or by long clicking on it.
To implement this, call the startActionMode() method on a viewor on your activity. This method gets an ActionMode.Callback object which is responsible for the life cycle of the contextual action bar.
You could also assign a context menu to a view via the registerForContextMenu(view) method. A context menu is also activated if the user «long presses» the view. The onCreateContextMenu() method is called every time a context menu is activated as the context menu is discarded after its usage. You should prefer the contextual action mode over the usage of context menus.
2.6. Contributing to the action bar with fragments
Fragments can also contribute entries to the toolbar bar.
To do this, call setHasOptionsMenu(true) in the onCreate() method of the fragment. The Android framework calls in this case the onCreateOptionsMenu() method in the fragment class. Here the fragment can adds menu items to the toolbar.
2.7. Changing the visibility of the toolbar bar
You can change the visibility of the toolbar at runtime. The following code demonstrates that.
You can also change the text which is displayed alongside the application icon at runtime. The following example shows that.
2.8. Assigning a Drawable
You also add a Drawable to the action bar as background via the ActionBar.setBackgroundDrawable() method.
The toolbar scales the image. Therefore it is best practice to provide a scalable drawable, e.g., a 9-patch or XML drawable.
As of Android 4.2 the background of the action bar can also be animated via an AnimationDrawable .
2.9. Dimming the navigation buttons
You can also dim the software navigation button in your Android application to have more space available. If the user touches the button of the screen, the navigation button is automatically shown again.
Dimming the navigation buttons is demonstrated by the following code snippet.
The following screenshots show an application with and without the navigation buttons.
2.10. Using immersive full screen mode
As of Android 4.4 (API 19) you can put your application into full screen mode. The first time this happens the system displays the user the info that he can restore the system bars with a downward swipe along the region where the system bars normally appear.
For example the following method also to put an activity into full screen mode.
2.11. Enabling the split toolbar
You can define that the toolbar should be automatically split by the system if not enough space is available.
You can activate this via the android:uiOptions=»SplitActionBarWhenNarrow» parameter in the declaration of your application activity in the AndroidManifest.xml file.
If this option is activated, Android has the option to split the toolbar. Whether to split is decided by the system at runtime. |
3. Exercise: Using the contextual action mode
3.1. Target
In this exercise you add a contextual action mode to one of your existing applications.
3.2. Create menu resource in the res/menu folder
For this, create a new menu XML resource with the actionmode.xml file name. See ActionMode.Callback callback as demonstrated in the following example code.
In your adapter implement a LongClickListener which triggers the contextual action mode.
4. Making the action bar dynamic
4.1. Custom views in the action bar
You can also add a custom view to the action bar, for example, a button or a text field.
For this you use the setCustomView method of the ActionView class. You also have to enable the display of custom views via the setDisplayOptions() method by passing in the ActionBar.DISPLAY_SHOW_CUSTOM flag.
For example, you can define a layout file which contains a EditText element.
This layout can be assigned in an activity to the action bar via the following code. The example code also attaches a listener to the custom view.
4.2. Action view
An action view _ is a widget that appears in the _action bar as a substitute for an action item’s button. You can, for example, use this feature to replace an action item with a ProgressBar view. An action view for an action can be defined via the android:actionLayout or android:actionViewClass attribute to specify either a layout resource or widget class to use.
This replacement is depicted in the following screenshots.
The following activity replaces the icon at runtime with an action view which contains a ProgressBar view.
The following code shows the layout used for the action view.
The following code shows the XML files for the menu.
5. Action provider
5.1. What is an action provider?
An action provider defines rich menu interaction in a single component. It can generate action views, which are used in the action bar, dynamically populate sub-menus of an action and handle default action invocations.
The base class for an action provider is the ActionProvider class.
Currently the Android platform provides two action providers: the MediaRouteActionProvider and the ShareActionProvider .
5.2. Example: usage of the ShareActionProvider
The following demonstrates the usage of the ShareActionProvider . This action provider allows you to grab selected content from applications which have registered the Intent.ACTION_SEND intent.
To use ShareActionProvider , you have to define a special menu entry for it and assign an intent which contains the sharing data to it.
6. Navigation via the application icon
6.1. Application icon as home
The action bar shows an icon of your application. This is called the home icon. You can assign an action to this icon. The recommendation is to return to the main activity in your program if the user selects this icon.
If the action is selected, the onOptionsItemSelected() method is called with an action which has the android.R.id.home ID.
Before Android 4.1, you had to use the android.R.id.home ID in the onOptionMenuItemSelected() method and enable the selection of the home button. This is demonstrated by the following code in which the SecondActivity activity defines the MainActivity as home.
As of Android 4.1 you can simply set the parentActivityName in the AndroidManifest.xml file pointing to the parent activity.
6.2. Application icon as Up button
You can use the application icon also as Up button, e.g., to go to the parent activity of the current activity. The back button on the device always returns to the previous activity.
Both can be different, for example, if the user started the option to write an email from the home screen, the back button will return the user to the home screen while the Up button would return the user to the activity which shows an overview of all emails.
To enable the Up display, you can use the following code snippet in your activity.
This snippet only enables the Up display on your home icon. You need to implement the correct behavior in your activity in the onOptionsItemSelected() method. The corresponding action still has the android.R.id.home ID. |
The difference between Up and the Back button can be confusing for the end user. If you decide to implement Up, in your application, it is recommended to perform some end user testing to see if the Up implementation is intuitive for them or not. |
7. Exercise: Using the toolbar
This exercise demonstrates how to use the toolbar widget in your Android application.
It is based on the fragment tutorial which can be found under: https:///www.vogella.com/tutorials/AndroidFragments/article.html You have to finish this tutorial before continuing this one.
8. Exercise: Add a toolbar to your application
8.1. Add a refresh icon
Continue to use the RSS Reader project. Create a new drawable called ic_refresh via the File New Vector Asset menu entry. Select a fitting image from the provided example images.
If the fill color does not fit to your styling, open the created drawable and adjust the color.
8.2. Add menu resources
Create a new XML resource for your menu called mainmenu.xml in your menu resource folder (create one, if the folder does not exist). The resulting XML file should look similar to the following listing.
8.3. Turn off the default action bar from the styling
Disable the default action bar one via the res/values/styles.xml file.
The following styling setting assumes that RssFeedActivity extends Activity . Please double-check this.
8.4. Add a toolbar view to your activity layout
Change the layout files of your RssfeedActivity activity to also contain a toolbar entry. For this you need to wrap your existing layout definition into another LinearLayout and add the toolbar to this second layout file.
Do the same for the layout for the portrait mode.
8.5. Adjust your activity
Change your RssfeedActivity class to the following code, to configure the toolbar view.
8.6. Run the application and test the toolbar
Run your application and validate that you can select both of your actions. Ensure that a Toast is displayed if you select the different entries.
If your device or emulator has an Option menu button, you will not see the overflow menu. You need to press the Option key to see the actions which are part of the overflow menu.
8.7. Trigger an intent via the toolbar
If the action_network action is selected, trigger the intent to control the network connectivity.
9. Trigger a method in your fragments via the toolbar
In this exercise you call a method in your list fragment based on the toolbar selection. It continues to use the RSS Reader project.
Create a updateListContent method in MyListFragment .
In your RssfeedActivity class, call the new method, if the action_refresh action is selected.
Источник