- Material Design. Динамический Toolbar на живом примере
- Начнём с постановки задачи
- Создаём xml файлы конфигураций
- Using the App Toolbar
- Android material toolbar color
- Define Design Support Library:
- Elements of Toolbar In Android:
- Basic Toolbar XML code:
- Setting Toolbar as An ActionBar:
- Attributes of Toolbar In Android:
- Important Methods of Toolbar:
- Toolbar Example 1 In Android Studio:
- Toolbar Example 2 In Android Studio:
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
Источник
Using the App Toolbar
Toolbar was introduced in Android Lollipop, API 21 release and is the spiritual 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.
Toolbar works well with apps targeted to API 21 and above. However, Android has updated the AppCompat support libraries so the Toolbar can be used on lower Android OS devices as well. In AppCompat, Toolbar is implemented in the androidx.appcompat.widget.Toolbar class.ura
There are two ways to use Toolbar:
- Use a Toolbar as an Action Bar 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 Action Bar would not support; for example, showing multiple toolbars on the screen, spanning only part of the width, and so on.
The Toolbar is a generalization of the ActionBar system. The key differences that distinguish the Toolbar from the ActionBar include:
- Toolbar is a View included in a layout like any other View
- As a regular View , the toolbar is easier to position, animate and control
- Multiple distinct Toolbar elements can be defined within a single activity
Keep in mind that you can also configure any Toolbar as an Activity’s ActionBar, meaning that your standard options menu actions will be display within.
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 AndroidX 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/values/styles.xml file:
Now you need to add a Toolbar to your Activity layout file. One of the biggest advantages of using the Toolbar widget is that you can place the view anywhere within your layout. Below we place the toolbar at the top of a LinearLayout like the standard ActionBar:
Note: You’ll want to add android:fitsSystemWindows=»true» (learn more) to the parent layout of the Toolbar to ensure that the height of the activity is calculated correctly.
As Toolbar is just a ViewGroup and can be styled and positioned like any other view. Note that this means if you are in a RelativeLayout , you need to ensure that all other views are positioned below the toolbar explicitly. The toolbar is not given any special treatment as a view.
Next, in your Activity or Fragment, set the Toolbar to act as the ActionBar by calling the setSupportActionBar(Toolbar) method:
Note: When using the support library, make sure that you are importing android.support.v7.widget.Toolbar and not android.widget.Toolbar .
Next, we need to make sure we have the action items listed within a menu resource file such as res/menu/menu_main.xml which is inflated above in onCreateOptionsMenu :
For more details about action items in the Toolbar including how to setup click handling, refer to our ActionBar guide. The above code results in the toolbar fully replacing the ActionBar at the top:
From this point on, all menu items are displayed in your Toolbar, populated via the standard options menu callbacks.
In many apps, the same toolbar can be used across multiple activities or in alternative layout resources for the same activity. In order to easily reuse the toolbar, we can leverage the layout include tag as follows. First, define your toolbar in a layout file in res/layout/toolbar_main.xml :
Next, we can use the tag to load the toolbar into our activity layout XML:
and then access the Toolbar by the include id instead:
This allows us to create a consistent navigation experience across activities or configuration changes.
The Toolbar can be customized in many ways leveraging various style properties including android:theme , app:titleTextAppearance , app:popupTheme . Each of these can be mapped to a style. Start with:
Now, we need to create the custom styles in res/values/styles.xml with:
This results in:
In certain situations, we might want to display an app icon within the Toolbar . This can be done by adding this code into the Activity
Next, we need to remove the left inset margin that pushes the icon over too far to the left by adding app:contentInsetStart to the Toolbar :
With that the icon should properly display within the Toolbar as expected.
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:
In certain cases, the status bar should be translucent such as:
To achieve this, first set these properties in your res/values/styles.xml within the main theme:
The activity or root layout that will have a transparent status bar needs have the fitsSystemWindows property set in the layout XML:
You should be all set. Refer to this stackoverflow post for more details.
If you want the status bar to be entirely transparent for KitKat and above, the easiest approach is to:
and then add this style to your res/values/styles.xml within the main theme:
You should be all set. Refer to this stackoverflow post for more details.
We can configure the Toolbar to react and change as the page scrolls:
For example, we can have the toolbar hide when the user scrolls down on a list or expand as the user scrolls to the header. There are many effects that can be configured by using the CoordinatorLayout. First, we need to make sure we add the jetpack libraries to our app/build.gradle file:
Next, inside the activity layout XML such as res/layout/activity_main.xml , we need to setup our coordinated layout with a Toolbar and a scrolling container such as a RecyclerView :
Of course, the RecyclerView could also be replaced with a FrameLayout which could then allow for fragments to be loaded instead:
This type of layout results in the following:
Refer to the guide on CoordinatorLayout and AppBarLayout for additional explanation and specifics. For troubleshooting, refer to this troubleshooting guide.
The proper way of reacting to simple scroll behavior is leveraging the CoordinatorLayout built into the Design Support Library as shown in the previous section. However, there are a few other relevant resources around reacting to scrolling events with a more manual approach:
- Hiding or Showing Toolbar on Scroll — Great guide on an alternate strategy not requiring the CoordinatorLayout to replicate the behavior of the «Google Play Music» app. Sample code can be found here.
- Hiding or Showing Toolbar using CoordinatorLayout — Great guide that outlines how to use CoordinatorLayout to hide the Toolbar and the FAB when the user scrolls.
With these methods, your app can replicate any scrolling behaviors seen in common apps with varying levels of difficulty not captured with the method shown above.
Источник
Android material toolbar color
In Android Toolbar is similar to an ActionBar(now called as App Bars). Toolbar is a Viewgroup that can be placed at anywhere in the Layout. We can easily replace an ActionBar with Toolbar.
Toolbar was introduced in Material Design in API level 21 (Android 5.0 i.e Lollipop). Material Design brings lot of new features in Android that changed a lot the visual design patterns regarding the designing of modern Android applications.
An Action bar is traditionally a part of an Activity opaque window decor controlled by the framework but a Toolbar may be placed at any level of nesting within a view hierarchy. Toolbar provides more feature than ActionBar. A Toolbar may contain a combination of elements from start to end.
Important Note: Toolbar’s are more flexible than ActionBar. We can easily modify its color, size and position. We can also add labels, logos, navigation icons and other views in it. In Material Design Android has updated the AppCompat support libraries so that we can use Toolbar’s in our devices running API Level 7 and up. In AppCompat, Toolbar is implemented in the android.support.v7.widget.Toolbar class.
Table Of Contents
Define Design Support Library:
To use Toolbar you need to add design support library in build.gradle file.
Gradle Scripts > build.gradle (Module:App) -> inside dependencies
Elements of Toolbar In Android:
In Android Toolbar has more features than ActionBar and we can easily replace a ActionBar with Toolbar. In Toolbar from start to end it may contain a combination of Elements. Below we describe each and every element of Toolbar.
Navigation Button: It may be a Navigation menu toggle, up arrow, close, done, collapse or any other glyph of the app’s choosing.
- Brand Logo Image: It may extend to the height of the toolbar and can be arbitrarily wide.
- Title and SubTitle: A title should be a signpost for the current position of Toolbar’s navigation hierarchy and the content contained there. Subtitle represents any extended information about the current content. If an app uses a logo then it should strongly consider omitting a title and subtitle.
- One or More Custom Views: An Application may add arbitrary child views to the Toolbar. If child view’s Toolbar.LayoutParams indicates CENTER_HORIZONTAL Gravity then view will attempt to center within the available space remaining in the Toolbar after all other element’s have been measured.
- Action Menu: The menu of Actions will pin to the end of the Toolbar offering a few important, typical or frequent actions along with an optional overflow menu for additional actions. Action buttons are aligned vertically within the Toolbar’s minimum height if we set.
Basic Toolbar XML code:
Setting Toolbar as An ActionBar:
We can easily replace ActionBar with Toolbar by using setSupportActionBar() method. Here is the code of replacing ActionBar with Toolbar.
Attributes of Toolbar In Android:
Now let’s we discuss some common attributes of a Toolbar that helps us to configure it in our layout (xml).
- id: This attribute is used to set the id for the Toolbar. Id is used to uniquely identify a Toolbar.
Below we set the id of the Toolbar.
logo: This attribute is used to set as the drawable logo that appears at the starting side of the Toolbar means just after the navigation button. We can also do this programmatically by using setLogo() method.Below we set the logo for the Toolbar.
logoDescription: This attribute is used to set the content description string to describe the appearance of the associated logo image. We can also do this programmatically by using setLogoDescription() method.
Below we set the description for the displayed logo.
navigationIcon: This attribute is used to set the Icon drawable for the navigation button that located at the start of the toolbar. We can also do this programmatically by using setNavigationIcon() method.Below we set the icon for the navigation button.
navigationContentDescription: This attribute is used to set the text for the description of navigation button. We can also do this programmatically by using setNavigationContentDescription() method.
Below we set the content description for the displayed icon of navigation button.
title: This attribute is used to set title for the Toolbar. We can also do this programmatically by using setTitle() method.
Below we set the title for the Toolbar.
titleTextColor: This attribute is used to set the color for the title text. We can also do this programmatically by using setTitleTextColor() method.Below we set the red color for the dispalyed title text.
subtitle: This attribute is used to set the sub title for the Toolbar. We can also do this programmatically by using setSubtitle() method.
Below we set the sub title for the Toolbar.
Important Methods of Toolbar:
Let’s we discuss some important methods of Toolbar that may be called in order to add Action icons manage the Toolbar.
Important Note: To understand below functions of Toolbar properly please do read 2nd example in this article.
- setLogo(int resId): This method is used to add a logo drawable from a resource id. Below we set a logo drawable in our Toolbar.
- setLogo(Drawable drawable): This method is also used to add a logo drawable in our Toolbar. In this method we set a drawable object. Below we set a drawable logo in our Toolbar.
- getLogo(): This method is used to get the logo icon from Toolbar. This method returns the Drawable logo which we set using setLogo() method.
Below we firstly set the drawable logo and then get the same from Toolbar.
setLogoDescription(CharSequence description): This method is used to set a description for the drawable logo of Toolbar.
Below we set the description for Toolbar’s logo.
setLogoDescription(int resId): This method is also used to set the description for drawable logo of the Toolbar. This method set the description from string file.
Below we set the description for Toolbar’s logo.
Below we set a navigation icon in the Toolbar from resource id.
Below we set the title for the Toolbar.
setTitle(CharSequence title): This method is also used to set the title for the Toolbar.
Below we set the title for the Toolbar.
setSubtitle(int resId): This method is used to set the sub Title for the Toolbar. In this method we set the sub title form string file.
Below we set the sub title for the Toolbar.
setSubtitle(CharSequence subtitle): This method is also used to set the sub title for the Toolbar.
Below we set the sub title for the Toolbar.
Below we set the description for Navigation Button.
Below we set the red color for the displayed text of title.
setSubtitleTextColor(int color): This method is used to set the text color for the displayed sub title.
Below we set the red color for the displayed sub text of title.
Toolbar Example 1 In Android Studio:
Below is the first example of Toolbar in which we create a Toolbar and replace it with ActionBar. In this examle we add action icons in Toobar and on click of navigation Button of Toolbar we open a Navigation Drawer. In our main layout we use Drawer Layout and Navigation View. Drawer Layout is the root layout in which we include a Toolbar and also define a FrameLayout and a Navigation View. In Navigation View we set the items from menu file and FrameLayout is used to replace the Fragments on the click of menu items. Whenever a user click on menu item, Fragment is replaced according to menu item’s id and a toast message with menu item title is displayed on the screen. We also create three Fragments that should be replaced on click of menu items
Step 1: Create a new project and name it ToolbarExample.
Step 2: Open Gradle Scripts > build.gradle and add Design support library dependency. If you are on the latest version of Android Studio you don’t need to add a compiled dependency for Appcombat v7 21 library if not then please make sure you add the line below in your gradel build dependencies.
apply plugin: ‘com.android.application’
Step 3: ActionBars are replaced with Toolbar so we can still use ActionBar but in our example we are going to make a Toolbar so go to your style.xml file and change the theme to “Theme.AppCompat.Light.NoActionBar” This theme helps us get rid of the ActionBar so we can make a Toolbar.
Step 4: Now let’s talk about the color scheme for our application. Open your color.xml file from values folder. In this XML file colorPrimary is the primary color for the app and colorPrimaryDark color is the color of the status bar. We can easily change our colors from this file.
Step 5: Open res -> layout -> activity_main.xml (or) main.xml and add following code:
In this step we define a DrawerLayout that is the parent layout in which we include a toolbar.xml file and also define a FrameLayout and a Navigation View. In Navigation View we set the items from menu file named “nav_items” and FrameLayout is used to replace the Fragments on the click of menu items.
Step 6: Open res -> menu -> nav_items.xml and add following code. Here we define the menu items.
Step 7: Now create a xml layouts by right clicking on res/layout -> New -> Layout Resource File and name it toolbar.xml
In this file we set the background color, navigation button and tilte for the Toolbar.
Step 8: Open src -> package -> MainActivity.java
In this step we open the MainActivity and add the code for initiates the views(DrawerLayout, Toolbar,NavigationView and other views). In this we replace the ActionBar with our ToolBar by using setSupportActionBar() method and then implment setNavigationOnClickListener event and add the code to open the drawer on click of navigation button. After that we implement setNavigationItemSelectedListener event on NavigationView so that we can replace the Fragments according to menu item’s id and a toast message with menu item’s title is displayed on the screen. In this I have added comments in code to help you to understand the code easily so make you read the comments.
Step 9: Now we need 3 fragments and 3 xml layouts. So create three fragments by right click on your package folder and create classes and name them as FirstFragment, SecondFragment and ThirdFragment and add the following code respectively.
Step 10: Now create 3 xml layouts by right clicking on res/layout -> New -> Layout Resource File and name them as fragment_first, fragment_ second and fragment_third and add the following code in respective files.
Here we will design the basic simple UI by using TextView in all xml’s.
Output:
Now run the App and you will see Menu icon and “AbhiAndroid” text written at the top which is created using Toolbar. Now click on menu and three items inside it will be shown. Now click on any of them and corresponding to it layout will open up.
Toolbar Example 2 In Android Studio:
Below is the simple example of Toolbar in which we create a Toolbar and replace it with our ActionBar. In this example we set Logo, title and menu for Toolbar. In our main layout we create a Toolbar and in Activity get the reference of Toolbar and set the title and logo on it. In this we use Activity’s overrided method onCreateOptionsMenu to set the menu items from menu file and onOptionsItemSelected to set click listeners on menu item’s. On click of menu item the title of menu is displayed on the screen with the help of Toast.
Step 1: Create a new project and name it SimpleToolbarExample.
Step 2: Open Gradle Scripts > If you are on the latest version of Android Studio you don’t need to add a compiled dependency for Appcombat v7 21 library if not then please make sure you add the line below in your gradel build dependencies.
Step 3: ActionBars are replaced with Toolbar so we can still use ActionBar but in our example we are going to make a Toolbar so go to your style.xml file and change the theme to “Theme.AppCompat.Light.NoActionBar” This theme helps us get rid of the ActionBar so we can make a Toolbar.
Step 4: Now let’s talk about the color scheme for our application. Open your color.xml file from values folder. In this XML file colorPrimary is the primary color for the app and colorPrimaryDark color is the color of the status bar. We can easily change our colors from this file.
Step 5: Open res -> layout -> activity_main.xml (or) main.xml and add following code:
In this step we define a Toolbar in our main XML file and set it’s background color and theme.
Step 6: Open res -> menu -> menu_main.xml and add following code:
In this step we create 3 menu items that will be displayed on Toolbar.
Step 7: Open src -> package -> MainActivity.java
In this step we open the MainActivity and add the code for initiates the Toolbar.. In this we replace the ActionBar with our ToolBar by using setSupportActionBar() method and also set the tiltle and logo for the Toolbar. After that we implement Activity’s overrided method onCreateOptionsMenu to set the menu items from menu file and onOptionsItemSelected to set click listeners on menu item’s. On click of menu item the tiltle of menu is displayed on the screen with the help of Toast. In this I have added comments in code to help you to understand the code easily so make sure you read the comments.
Output:
Now run the App and you will see Toolbar at the top. Click on it and message created using Toast will be displayed.
Источник