Как легко сделать Navigation Drawer и вкладки, используемые в популярных приложениях от Google
При использовании популярного приложения Play Маркет многие обратили внимание на вкладки для переключения контента. Такое применение вкладок можно найти и в других приложениях от Google, таких как Play Музыка, Play Пресса.
На этой почве возникает интерес, а иногда и необходимость (если заказчик просит) реализовать увиденное. Я не стал исключением и при проектировании нового приложения, дизайн которого был набросан на черновике, присутствовал очень схожий дизайн, хотя и имел всего несколько вкладок. Казалось бы, что сложного? Сейчас откроем официальную документацию, просмотрим необходимые разделы и приступим к делу. Но, изучив документацию, не смог обнаружить соответствующих примеров — и тут же возник новый вопрос. Почему Android разработчики из компании Google по умолчанию не предоставляют примеров с необходимой функциональностью, чтобы сделать это довольно просто, ведь это реализовано в каждом их приложении? Также, погуглив, нашлись аналогичные вопросы на Stack Overflow. Исходя из этого, оказалось, что существует проблема или, по крайней мере, нераскрытый вопрос, в котором следует разобраться.
Ниже хочу рассказать о том, как всё же можно реализовать паттерн Navigation Drawer вместе с вкладками, как в популярных приложениях от Google.
В примере будет использоваться интегрированная среда разработки Eclipse, но все действия можно будет воспроизвести, используя и другие среды, к примеру, недавно вышедшую и набирающую популярность Android Studio от компании Google, основанную на IntelliJ IDEA.
Создание проекта
Создадим новый проект. Для этого перейдем в File > New > Android Application Project. Заполним поля, такие как имя приложения, пакета и версии SDK. Далее проследуем по экранам, нажимая клавишу Next и оставляя всё по умолчанию.
Среда разработки для нас создаст новый проект со стандартной структурой.
Пример будет работать, начиная с API версии 8. Это обосновано тем, что пользователи ещё пользуются девайсами со старой версией Android. Ниже приведены данные о количестве устройств, работающих под управлением различных версий платформы на состояние 12.08.2014.
Action Bar для API 8
Но ActionBar, сочетающий в себе заголовок и меню, появился начиная с Android 3.0 (API 11). Для того, чтобы его использовать, необходимо подключить к проекту библиотеку Android-Support-v7-Appcompat, любезно предоставленную компанией Google. Детальную инструкцию по добавлению библиотеки к проекту можно найти по адресу: developer.android.com/tools/support-library/setup.html
Есть две возможности добавить библиотеку к проекту — без использования ресурсов и с использованием. В реализации этого проекта будет использоваться библиотека с использованием ресурсов. После того, как библиотека будет добавлена в дерево проектов, необходимо перейти в Properties, нажав по проекту правой клавишей мыши и выбрать в категориях Android, затем нажать клавишу Add. В появившемся списке выбрать android-support-v7-appcompat и нажать OK > Apply > OK. Библиотека добавлена в проект. Но если попытаться запустить приложение, то ActionBar будет ещё не виден. Необходимо в res/values/styles.xml изменить строчку:
в res/values-v11/styles.xml изменить строчку:
в res/values-v14/styles.xml изменить строчку:
Также в главной активности необходимо наследоваться не от Activity, а от ActionBarActivity (android.support.v7.app.ActionBarActivity). После проделанных действий и запуска приложения можно увидеть ActionBar, включая и на ранних версиях API.
Зайдем в папку Menu и отредактируем файл main.xml, чтобы выглядел следующим образом:
Необходимо обратить внимание на следующую строчку: xmlns:sabd=http://schemas.android.com/apk/res-auto. Теперь необходимо атрибут showAsAction задавать следующим образом: sabd:showAsAction=» «. Также следует зайти в strings.xml и изменить строчку:
Теперь меню будет иметь привычный вид.
Внедрение бокового меню
Следующим нашим шагом будет внедрение бокового меню (Navigation Drawer). Это панель, которая отображает основные параметры навигации приложения в левом краю экрана. Раскрывается жестом от левого края экрана или по нажатию на значок приложения в панели действий.
Изменим основной ресурс activity_main.xml:
Боковое меню будет заполняться в ListView, для этого добавим в string.xml строковый массив названий:
Необходимо определить, как будет выглядеть позиция в ListView. Для этого создадим в папке layout новый ресурс с названием drawer_list_item.xml:
Для функционирования работы созданного ресурса далее дополнительно создадим в папке res новую папку drawable и в ней создадим селектор activated_background.xml, поместив в него:
В папке values создадим ресурс для цветов color.xml и поместим туда цвет, который будет отвечать за выделение пункта списка в боковом меню:
Следующим шагом будет добавление иконок в приложение, а именно значка бокового меню. Скачать архив иконок можно по прямой ссылке с официального сайта Google по адресу: developer.android.com/downloads/design/Android_Design_Icons_20130926.zip. В архиве будет многочисленное число иконок для разных событий, но нужны иконки из папки Navigation_Drawer_Indicator. Следует каждый графический объект с названием ic_drawer.png поместить в проект с правильной плотностью вида drawable-.
Для оповещения о том, что меню открыто или закрыто, добавим в string.xml ещё записи:
Заодно удалим из ресурсов следующую строчку, так как она нам уже не понадобится:
Главное Activity
Теперь необходимо переписать класс MainActivity. Для поддержки старых устройств мы используем библиотеку поддержки Android Support Library (v4), при создании проекта она автоматически добавляется в папку libs. В листинге присутствуют комментарии, которые смогут дать возможность понять, как работает код. Для дополнительной информации можно воспользоваться официальной документацией: developer.android.com/training/implementing-navigation/nav-drawer.html. Ниже листинг.
Добавим фрагменты
Добавим новый пакет fragments, который будет содержать фрагменты. И поместим в него три класса-фрагмента. Для примера я выложу код одного фрагмента, остальные необходимо сделать по аналогии, изменив название класса, конструктора и разметки.
Также добавим в ресурсы разметку для этих классов. Для примера, выложу разметку одного фрагмента screen_one.xml. В остальных необходимо изменить только текст атрибута android:text:
Добавим в string.xml ещё несколько строчек, которые будут информировать о том, какой экран открыт из меню:
На этом этапе реализация Navigation Drawer завершена. Если запустить приложение, мы увидим работу бокового меню. Как на старых устройствах:
Внедрение вкладок
Теперь приступаем к добавлению вкладок. Первым делом, чтобы нам правильно добавить вкладки, необходимо понять принцип расположения элементов навигации. Существует строгая иерархия, в которой должны располагаться вкладки:
0 — Navigation Drawer занимает самый верхний уровень навигации.
1 — Action Bar второй уровень.
2 — Вкладки нижний уровень.
Для реализации необходимо использовать два дополнительных класса, которые Google снова любезно предоставляет. Это классы SlidingTabLayout и SlidingTabStrip. Добавим их в проект. Для этого создадим новый пакет view, там создадим новые классы с соответствующим названием и переместим в них код. При возникновении ошибок в методе createDefaultTabView(Context context) класса SlidingTabLayout следует подавить предупреждение, дописав над методом @SuppressLint(«NewApi»)
Внесем все новые изменения для фрагмента ScreenOne. Первым делом изменим разметку screen_one.xml:
Важно использовать полное имя пакета для SlidingTabLayout, так как он включен в наш проект. Далее создадим новую разметку в папке layout для вкладок pager_item.xml:
Войдем в string.xml и изменим строчку:
Так как нам уже не понадобится строковый ресурс, вместо него мы сразу отобразим ViewPager с номером вкладки. Далее изменим класс ScreenOne соответствующим образом:
Теперь можно запустить приложение и увидеть, как работают вкладки как на старом устройстве:
Можно заметить, что боковое меню покрывает вкладки, как в правилах навигации и приложениях от Google:
На этом пример полностью завершён и его можно использовать.
Вкладки Action Bar
Хочется отметить ещё один последний, важный момент. Многие «путают» реализованные вкладки с вкладками ActionBar, они выглядят похоже:
Но у них реализация другая, поведение и в горизонтальной ориентации переносятся в ActionBar:
Если добавить вкладки через ActionBar, то боковое меню Navigation Drawer не перекроет вкладки, а выедет под ними:
На этом всё. Спасибо за внимание и приятного вам кодинга.
Среда разработки – Eclipse
Минимальная версия Android – >= 8
Action Bar
The action bar is a window feature that identifies the user location, and provides user actions and navigation modes. Using the action bar offers your users a familiar interface across applications that the system gracefully adapts for different screen configurations.
Figure 1. An action bar that includes the [1] app icon, [2] two action items, and [3] action overflow.
The action bar provides several key functions:
- Provides a dedicated space for giving your app an identity and indicating the user’s location in the app.
- Makes important actions prominent and accessible in a predictable way (such as Search).
- Supports consistent navigation and view switching within apps (with tabs or drop-down lists).
For more information about the action bar’s interaction patterns and design guidelines, see the Action Bar design guide.
The ActionBar APIs were first added in Android 3.0 (API level 11) but they are also available in the Support Library for compatibility with Android 2.1 (API level 7) and above.
This guide focuses on how to use the support library’s action bar, but if your app supports only Android 3.0 or higher, you should use the ActionBar APIs in the framework. Most of the APIs are the same—but reside in a different package namespace—with a few exceptions to method names or signatures that are noted in the sections below.
Caution: Be certain you import the ActionBar class (and related APIs) from the appropriate package:
- If supporting API levels lower than 11:
import android.support.v7.app.ActionBar - If supporting only API level 11 and higher:
import android.app.ActionBar
Note: If you’re looking for information about the contextual action bar for displaying contextual action items, see the Menu guide.
Adding the Action Bar
As mentioned above, this guide focuses on how to use the ActionBar APIs in the support library. So before you can add the action bar, you must set up your project with the appcompat v7 support library by following the instructions in the Support Library Setup.
Once your project is set up with the support library, here’s how to add the action bar:
- Create your activity by extending ActionBarActivity .
- Use (or extend) one of the Theme.AppCompat themes for your activity. For example:
Now your activity includes the action bar when running on Android 2.1 (API level 7) or higher.
On API level 11 or higher
The action bar is included in all activities that use the Theme.Holo theme (or one of its descendants), which is the default theme when either the targetSdkVersion or minSdkVersion attribute is set to «11» or higher. If you don’t want the action bar for an activity, set the activity theme to Theme.Holo.NoActionBar .
Removing the action bar
You can hide the action bar at runtime by calling hide() . For example:
On API level 11 or higher
Get the ActionBar with the getActionBar() method.
When the action bar hides, the system adjusts your layout to fill the screen space now available. You can bring the action bar back by calling show() .
Beware that hiding and removing the action bar causes your activity to re-layout in order to account for the space consumed by the action bar. If your activity often hides and shows the action bar, you might want to enable overlay mode. Overlay mode draws the action bar in front of your activity layout, obscuring the top portion. This way, your layout remains fixed when the action bar hides and re-appears. To enable overlay mode, create a custom theme for your activity and set windowActionBarOverlay to true . For more information, see the section below about Styling the Action Bar.
Using a logo instead of an icon
By default, the system uses your application icon in the action bar, as specified by the icon attribute in the <application> or <activity> element. However, if you also specify the logo attribute, then the action bar uses the logo image instead of the icon.
A logo should usually be wider than the icon, but should not include unnecessary text. You should generally use a logo only when it represents your brand in a traditional format that users recognize. A good example is the YouTube app’s logo—the logo represents the expected user brand, whereas the app’s icon is a modified version that conforms to the square requirement for the launcher icon.
Adding Action Items
Figure 2. Action bar with three action buttons and the overflow button.
The action bar provides users access to the most important action items relating to the app’s current context. Those that appear directly in the action bar with an icon and/or text are known as action buttons. Actions that can’t fit in the action bar or aren’t important enough are hidden in the action overflow. The user can reveal a list of the other actions by pressing the overflow button on the right side (or the device Menu button, if available).
When your activity starts, the system populates the action items by calling your activity’s onCreateOptionsMenu() method. Use this method to inflate a menu resource that defines all the action items. For example, here’s a menu resource defining a couple of menu items:
Then in your activity’s onCreateOptionsMenu() method, inflate the menu resource into the given Menu to add each item to the action bar:
To request that an item appear directly in the action bar as an action button, include showAsAction=»ifRoom» in the <item> tag. For example:
If there’s not enough room for the item in the action bar, it will appear in the action overflow.
Using XML attributes from the support library
Notice that the showAsAction attribute above uses a custom namespace defined in the <menu> tag. This is necessary when using any XML attributes defined by the support library, because these attributes do not exist in the Android framework on older devices. So you must use your own namespace as a prefix for all attributes defined by the support library.
If your menu item supplies both a title and an icon—with the title and icon attributes—then the action item shows only the icon by default. If you want to display the text title, add «withText» to the showAsAction attribute. For example:
Note: The «withText» value is a hint to the action bar that the text title should appear. The action bar will show the title when possible, but might not if an icon is available and the action bar is constrained for space.
You should always define the title for each item even if you don’t declare that the title appear with the action item, for the following reasons:
- If there’s not enough room in the action bar for the action item, the menu item appears in the overflow where only the title appears.
- Screen readers for sight-impaired users read the menu item’s title.
- If the action item appears with only the icon, a user can long-press the item to reveal a tool-tip that displays the action title.
The icon is optional, but recommended. For icon design recommendations, see the Iconography design guide. You can also download a set of standard action bar icons (such as for Search or Discard) from the Downloads page.
You can also use «always» to declare that an item always appear as an action button. However, you should not force an item to appear in the action bar this way. Doing so can create layout problems on devices with a narrow screen. It’s best to instead use «ifRoom» to request that an item appear in the action bar, but allow the system to move it into the overflow when there’s not enough room. However, it might be necessary to use this value if the item includes an action view that cannot be collapsed and must always be visible to provide access to a critical feature.
Handling clicks on action items
When the user presses an action, the system calls your activity’s onOptionsItemSelected() method. Using the MenuItem passed to this method, you can identify the action by calling getItemId() . This returns the unique ID provided by the <item> tag’s id attribute so you can perform the appropriate action. For example:
Note: If you inflate menu items from a fragment, via the Fragment class’s onCreateOptionsMenu() callback, the system calls onOptionsItemSelected() for that fragment when the user selects one of those items. However, the activity gets a chance to handle the event first, so the system first calls onOptionsItemSelected() on the activity, before calling the same callback for the fragment. To ensure that any fragments in the activity also have a chance to handle the callback, always pass the call to the superclass as the default behavior instead of returning false when you do not handle the item.
Figure 3. Mock-ups showing an action bar with tabs (left), then with split action bar (middle); and with the app icon and title disabled (right).
Using split action bar
Split action bar provides a separate bar at the bottom of the screen to display all action items when the activity is running on a narrow screen (such as a portrait-oriented handset).
Separating the action items this way ensures that a reasonable amount of space is available to display all your action items on a narrow screen, while leaving room for navigation and title elements at the top.
To enable split action bar when using the support library, you must do two things:
- Add uiOptions=»splitActionBarWhenNarrow» to each <activity> element or to the <application> element. This attribute is understood only by API level 14 and higher (it is ignored by older versions).
- To support older versions, add a <meta-data> element as a child of each <activity> element that declares the same value for «android.support.UI_OPTIONS» .
Using split action bar also allows navigation tabs to collapse into the main action bar if you remove the icon and title (as shown on the right in figure 3). To create this effect, disable the action bar icon and title with setDisplayShowHomeEnabled(false) and setDisplayShowTitleEnabled(false) .
Navigating Up with the App Icon
Design Guide
Navigation with Back and Up
Figure 4. The Up button in Gmail.
Enabling the app icon as an Up button allows the user to navigate your app based on the hierarchical relationships between screens. For instance, if screen A displays a list of items, and selecting an item leads to screen B, then screen B should include the Up button, which returns to screen A.
Note: Up navigation is distinct from the back navigation provided by the system Back button. The Back button is used to navigate in reverse chronological order through the history of screens the user has recently worked with. It is generally based on the temporal relationships between screens, rather than the app’s hierarchy structure (which is the basis for up navigation).
To enable the app icon as an Up button, call setDisplayHomeAsUpEnabled() . For example:
Now the icon in the action bar appears with the Up caret (as shown in figure 4). However, it won’t do anything by default. To specify the activity to open when the user presses Up button, you have two options:
-
Specify the parent activity in the manifest file.
This is the best option when the parent activity is always the same. By declaring in the manifest which activity is the parent, the action bar automatically performs the correct action when the user presses the Up button.
Beginning in Android 4.1 (API level 16), you can declare the parent with the parentActivityName attribute in the <activity> element.
To support older devices with the support library, also include a <meta-data> element that specifies the parent activity as the value for android.support.PARENT_ACTIVITY . For example:
Once the parent activity is specified in the manifest like this and you enable the Up button with setDisplayHomeAsUpEnabled() , your work is done and the action bar properly navigates up.
This is appropriate when the parent activity may be different depending on how the user arrived at the current screen. That is, if there are many paths that the user could have taken to reach the current screen, the Up button should navigate backward along the path the user actually followed to get there.
The system calls getSupportParentActivityIntent() when the user presses the Up button while navigating your app (within your app’s own task). If the activity that should open upon up navigation differs depending on how the user arrived at the current location, then you should override this method to return the Intent that starts the appropriate parent activity.
The system calls onCreateSupportNavigateUpTaskStack() for your activity when the user presses the Up button while your activity is running in a task that does not belong to your app. Thus, you must use the TaskStackBuilder passed to this method to construct the appropriate back stack that should be synthesized when the user navigates up.
Even if you override getSupportParentActivityIntent() to specify up navigation as the user navigates your app, you can avoid the need to implement onCreateSupportNavigateUpTaskStack() by declaring «default» parent activities in the manifest file as shown above. Then the default implementation of onCreateSupportNavigateUpTaskStack() will synthesize a back stack based on the parent activities declared in the manifest.
Note: If you’ve built your app hierarchy using a series of fragments instead of multiple activities, then neither of the above options will work. Instead, to navigate up through your fragments, override onSupportNavigateUp() to perform the appropriate fragment transaction—usually by popping the current fragment from the back stack by calling popBackStack() .
For more information about implementing Up navigation, read Providing Up Navigation.
Adding an Action View
Figure 5. An action bar with a collapsible SearchView .
An action view is a widget that appears in the action bar as a substitute for an action button. An action view provides fast access to rich actions without changing activities or fragments, and without replacing the action bar. For example, if you have an action for Search, you can add an action view to embeds a SearchView widget in the action bar, as shown in figure 5.
To declare an action view, use either the actionLayout or actionViewClass attribute to specify either a layout resource or widget class to use, respectively. For example, here’s how to add the SearchView widget:
Notice that the showAsAction attribute also includes the «collapseActionView» value. This is optional and declares that the action view should be collapsed into a button. (This behavior is explained further in the following section about Handling collapsible action views.)
If you need to configure the action view (such as to add event listeners), you can do so during the onCreateOptionsMenu() callback. You can acquire the action view object by calling the static method MenuItemCompat.getActionView() and passing it the corresponding MenuItem . For example, the search widget from the above sample is acquired like this:
On API level 11 or higher
Get the action view by calling getActionView() on the corresponding MenuItem :
For more information about using the search widget, see Creating a Search Interface.
Handling collapsible action views
To preserve the action bar space, you can collapse your action view into an action button. When collapsed, the system might place the action into the action overflow, but the action view still appears in the action bar when the user selects it. You can make your action view collapsible by adding «collapseActionView» to the showAsAction attribute, as shown in the XML above.
Because the system expands the action view when the user selects the action, you do not need to respond to the item in the onOptionsItemSelected() callback. The system still calls onOptionsItemSelected() , but if you return true (indicating you’ve handled the event instead), then the action view will not expand.
The system also collapses your action view when the user presses the Up button or Back button.
If you need to update your activity based on the visibility of your action view, you can receive callbacks when the action is expanded and collapsed by defining an OnActionExpandListener and passing it to setOnActionExpandListener() . For example:
Adding an Action Provider
Figure 6. An action bar with ShareActionProvider expanded to show share targets.
Similar to an action view, an action provider replaces an action button with a customized layout. However, unlike an action view, an action provider takes control of all the action’s behaviors and an action provider can display a submenu when pressed.
To declare an action provider, supply the actionViewClass attribute in the menu <item> tag with a fully-qualified class name for an ActionProvider .
You can build your own action provider by extending the ActionProvider class, but Android provides some pre-built action providers such as ShareActionProvider , which facilitates a «share» action by showing a list of possible apps for sharing directly in the action bar (as shown in figure 6).
Because each ActionProvider class defines its own action behaviors, you don’t need to listen for the action in the onOptionsItemSelected() method. If necessary though, you can still listen for the click event in the onOptionsItemSelected() method in case you need to simultaneously perform another action. But be sure to return false so that the the action provider still receives the onPerformDefaultAction() callback to perform its intended action.
However, if the action provider provides a submenu of actions, then your activity does not receive a call to onOptionsItemSelected() when the user opens the list or selects one of the submenu items.
Using the ShareActionProvider
To add a «share» action with ShareActionProvider , define the actionProviderClass for an <item> tag with the ShareActionProvider class. For example:
Now the action provider takes control of the action item and handles both its appearance and behavior. But you must still provide a title for the item to be used when it appears in the action overflow.
The only thing left to do is define the Intent you want to use for sharing. To do so, edit your onCreateOptionsMenu() method to call MenuItemCompat.getActionProvider() and pass it the MenuItem holding the action provider. Then call setShareIntent() on the returned ShareActionProvider and pass it an ACTION_SEND intent with the appropriate content attached.
You should call setShareIntent() once during onCreateOptionsMenu() to initialize the share action, but because the user context might change, you must update the intent any time the shareable content changes by again calling setShareIntent() .
The ShareActionProvider now handles all user interaction with the item and you do not need to handle click events from the onOptionsItemSelected() callback method.
By default, the ShareActionProvider retains a ranking for each share target based on how often the user selects each one. The share targets used more frequently appear at the top of the drop-down list and the target used most often appears directly in the action bar as the default share target. By default, the ranking information is saved in a private file with a name specified by DEFAULT_SHARE_HISTORY_FILE_NAME . If you use the ShareActionProvider or an extension of it for only one type of action, then you should continue to use this default history file and there’s nothing you need to do. However, if you use ShareActionProvider or an extension of it for multiple actions with semantically different meanings, then each ShareActionProvider should specify its own history file in order to maintain its own history. To specify a different history file for the ShareActionProvider , call setShareHistoryFileName() and provide an XML file name (for example, «custom_share_history.xml» ).
Note: Although the ShareActionProvider ranks share targets based on frequency of use, the behavior is extensible and extensions of ShareActionProvider can perform different behaviors and ranking based on the history file (if appropriate).
Creating a custom action provider
Creating your own action provider allows you to re-use and manage dynamic action item behaviors in a self-contained module, rather than handle action item transformations and behaviors in your fragment or activity code. As shown in the previous section, Android already provides an implementation of ActionProvider for share actions: the ShareActionProvider .
To create your own action provider for a different action, simply extend the ActionProvider class and implement its callback methods as appropriate. Most importantly, you should implement the following:
ActionProvider() This constructor passes you the application Context , which you should save in a member field to use in the other callback methods. onCreateActionView(MenuItem) This is where you define the action view for the item. Use the Context acquired from the constructor to instantiate a LayoutInflater and inflate your action view layout from an XML resource, then hook up event listeners. For example: onPerformDefaultAction() The system calls this when the menu item is selected from the action overflow and the action provider should perform a default action for the menu item.
However, if your action provider provides a submenu, through the onPrepareSubMenu() callback, then the submenu appears even when the action provider is placed in the action overflow. Thus, onPerformDefaultAction() is never called when there is a submenu.
Note: An activity or a fragment that implements onOptionsItemSelected() can override the action provider’s default behavior (unless it uses a submenu) by handling the item-selected event (and returning true ), in which case, the system does not call onPerformDefaultAction() .
Adding Navigation Tabs
Figure 7. Action bar tabs on a wide screen.
Design Guide
Also read
Creating Swipe Views with Tabs
Figure 8. Tabs on a narrow screen.
Tabs in the action bar make it easy for users to explore and switch between different views in your app. The tabs provided by the ActionBar are ideal because they adapt to different screen sizes. For example, when the screen is wide enough the tabs appear in the action bar alongside the action buttons (such as when on a tablet, shown in figure 7), while when on a narrow screen they appear in a separate bar (known as the «stacked action bar», shown in figure 8). In some cases, the Android system will instead show your tab items as a drop-down list to ensure the best fit in the action bar.
To get started, your layout must include a ViewGroup in which you place each Fragment associated with a tab. Be sure the ViewGroup has a resource ID so you can reference it from your code and swap the tabs within it.
Once you determine where the fragments appear in the layout, the basic procedure to add tabs is:
- Implement the ActionBar.TabListener interface. This interface provides callbacks for tab events, such as when the user presses one so you can swap the tabs.
- For each tab you want to add, instantiate an ActionBar.Tab and set the ActionBar.TabListener by calling setTabListener() . Also set the tab’s title and with setText() (and optionally, an icon with setIcon() ).
- Then add each tab to the action bar by calling addTab() .
Notice that the ActionBar.TabListener callback methods don’t specify which fragment is associated with the tab, but merely which ActionBar.Tab was selected. You must define your own association between each ActionBar.Tab and the appropriate Fragment that it represents. There are several ways you can define the association, depending on your design.
For example, here’s how you might implement the ActionBar.TabListener such that each tab uses its own instance of the listener:
Caution: You must not call commit() for the fragment transaction in each of these callbacks—the system calls it for you and it may throw an exception if you call it yourself. You also cannot add these fragment transactions to the back stack.
In this example, the listener simply attaches ( attach() ) a fragment to the activity layout—or if not instantiated, creates the fragment and adds ( add() ) it to the layout (as a child of the android.R.id.content view group)—when the respective tab is selected, and detaches ( detach() ) it when the tab is unselected.
All that remains is to create each ActionBar.Tab and add it to the ActionBar . Additionally, you must call setNavigationMode(NAVIGATION_MODE_TABS) to make the tabs visible.
For example, the following code adds two tabs using the listener defined above:
If your activity stops, you should retain the currently selected tab with the saved instance state so you can open the appropriate tab when the user returns. When it’s time to save the state, you can query the currently selected tab with getSelectedNavigationIndex() . This returns the index position of the selected tab.
Caution: It’s important that you save the state of each fragment so when users switch fragments with the tabs and then return to a previous fragment, it looks the way it did when they left. Some of the state is saved by default, but you may need to manually save state for customized views. For information about saving the state of your fragment, see the Fragments API guide.
Note: The above implementation for ActionBar.TabListener is one of several possible techniques. Another popular option is to use ViewPager to manage the fragments so users can also use a swipe gesture to switch tabs. In this case, you simply tell the ViewPager the current tab position in the onTabSelected() callback. For more information, read Creating Swipe Views with Tabs.
Adding Drop-down Navigation
Figure 9. A drop-down navigation list in the action bar.
As another mode of navigation (or filtering) for your activity, the action bar offers a built in drop-down list (also known as a «spinner»). For example, the drop-down list can offer different modes by which content in the activity is sorted.
Using the drop-down list is useful when changing the content is important but not necessarily a frequent occurrence. In cases where switching the content is more frequent, you should use navigation tabs instead.
The basic procedure to enable drop-down navigation is:
- Create a SpinnerAdapter that provides the list of selectable items for the drop-down and the layout to use when drawing each item in the list.
- Implement ActionBar.OnNavigationListener to define the behavior that occurs when the user selects an item from the list.
- During your activity’s onCreate() method, enable the action bar’s drop-down list by calling setNavigationMode(NAVIGATION_MODE_LIST) .
- Set the callback for the drop-down list with setListNavigationCallbacks() . For example:
This procedure is relatively short, but implementing the SpinnerAdapter and ActionBar.OnNavigationListener is where most of the work is done. There are many ways you can implement these to define the functionality for your drop-down navigation and implementing various types of SpinnerAdapter is beyond the scope of this document (you should refer to the SpinnerAdapter class reference for more information). However, below is an example for a SpinnerAdapter and ActionBar.OnNavigationListener to get you started (click the title to reveal the sample).
Example SpinnerAdapter and OnNavigationListener
SpinnerAdapter is an adapter that provides data for a spinner widget, such as the drop-down list in the action bar. SpinnerAdapter is an interface that you can implement, but Android includes some useful implementations that you can extend, such as ArrayAdapter and SimpleCursorAdapter . For example, here’s an easy way to create a SpinnerAdapter by using ArrayAdapter implementation, which uses a string array as the data source:
The createFromResource() method takes three parameters: the application Context , the resource ID for the string array, and the layout to use for each list item.
A string array defined in a resource looks like this:
The ArrayAdapter returned by createFromResource() is complete and ready for you to pass it to setListNavigationCallbacks() (in step 4 from above). Before you do, though, you need to create the OnNavigationListener .
Your implementation of ActionBar.OnNavigationListener is where you handle fragment changes or other modifications to your activity when the user selects an item from the drop-down list. There’s only one callback method to implement in the listener: onNavigationItemSelected() .
The onNavigationItemSelected() method receives the position of the item in the list and a unique item ID provided by the SpinnerAdapter .
Here’s an example that instantiates an anonymous implementation of OnNavigationListener , which inserts a Fragment into the layout container identified by R.id.fragment_container :
This instance of OnNavigationListener is complete and you can now call setListNavigationCallbacks() (in step 4), passing the ArrayAdapter and this OnNavigationListener .
In this example, when the user selects an item from the drop-down list, a fragment is added to the layout (replacing the current fragment in the R.id.fragment_container view). The fragment added is given a tag that uniquely identifies it, which is the same string used to identify the fragment in the drop-down list.
Here’s a look at the ListContentFragment class that defines each fragment in this example:
Styling the Action Bar
If you want to implement a visual design that represents your app’s brand, the action bar allows you to customize each detail of its appearance, including the action bar color, text colors, button styles, and more. To do so, you need to use Android’s style and theme framework to restyle the action bar using special style properties.
Caution: For all background drawables you provide, be sure to use Nine-Patch drawables to allow stretching. The nine-patch image should be smaller than 40dp tall and 30dp wide.
General appearance
The default for this style for this is Widget.AppCompat.ActionBar , which is what you should use as the parent style.
Supported styles include:
background Defines a drawable resource for the action bar background. backgroundStacked Defines a drawable resource for the stacked action bar (the tabs). backgroundSplit Defines a drawable resource for the split action bar. actionButtonStyle Defines a style resource for action buttons.
The default for this style for this is Widget.AppCompat.ActionButton , which is what you should use as the parent style.
actionOverflowButtonStyle Defines a style resource for overflow action items.
The default for this style for this is Widget.AppCompat.ActionButton.Overflow , which is what you should use as the parent style.
displayOptions Defines one or more action bar display options, such as whether to use the app logo, show the activity title, or enable the Up action. See displayOptions for all possible values. divider Defines a drawable resource for the divider between action items. titleTextStyle Defines a style resource for the action bar title.
The default for this style for this is TextAppearance.AppCompat.Widget.ActionBar.Title , which is what you should use as the parent style.
windowActionBarOverlay Declares whether the action bar should overlay the activity layout rather than offset the activity’s layout position (for example, the Gallery app uses overlay mode). This is false by default.
Normally, the action bar requires its own space on the screen and your activity layout fills in what’s left over. When the action bar is in overlay mode, your activity layout uses all the available space and the system draws the action bar on top. Overlay mode can be useful if you want your content to keep a fixed size and position when the action bar is hidden and shown. You might also like to use it purely as a visual effect, because you can use a semi-transparent background for the action bar so the user can still see some of your activity layout behind the action bar.
Note: The Holo theme families draw the action bar with a semi-transparent background by default. However, you can modify it with your own styles and the DeviceDefault theme on different devices might use an opaque background by default.
When overlay mode is enabled, your activity layout has no awareness of the action bar lying on top of it. So, you must be careful not to place any important information or UI components in the area overlaid by the action bar. If appropriate, you can refer to the platform’s value for actionBarSize to determine the height of the action bar, by referencing it in your XML layout. For example:
You can also retrieve the action bar height at runtime with getHeight() . This reflects the height of the action bar at the time it’s called, which might not include the stacked action bar (due to navigation tabs) if called during early activity lifecycle methods. To see how you can determine the total height at runtime, including the stacked action bar, see the TitlesFragment class in the Honeycomb Gallery sample app.
Action items
The default for this style for this is Widget.AppCompat.ActionButton , which is what you should use as the parent style.
actionBarItemBackground Defines a drawable resource for each action item’s background. This should be a state-list drawable to indicate different selected states. itemBackground Defines a drawable resource for each action overflow item’s background. This should be a state-list drawable to indicate different selected states. actionBarDivider Defines a drawable resource for the divider between action items. actionMenuTextColor Defines a color for text that appears in an action item. actionMenuTextAppearance Defines a style resource for text that appears in an action item. actionBarWidgetTheme Defines a theme resource for widgets that are inflated into the action bar as action views.
Navigation tabs
The default for this style for this is Widget.AppCompat.ActionBar.TabView , which is what you should use as the parent style.
actionBarTabBarStyle Defines a style resource for the thin bar that appears below the navigation tabs.
The default for this style for this is Widget.AppCompat.ActionBar.TabBar , which is what you should use as the parent style.
actionBarTabTextStyle Defines a style resource for text in the navigation tabs.
The default for this style for this is Widget.AppCompat.ActionBar.TabText , which is what you should use as the parent style.
Drop-down lists
The default for this style for this is Widget.AppCompat.Spinner.DropDown.ActionBar , which is what you should use as the parent style.
Example theme
Here’s an example that defines a custom theme for an activity, CustomActivityTheme , that includes several styles to customize the action bar.
Notice that there are two versions for each action bar style property. The first one includes the android: prefix on the property name to support API levels 11 and higher that include these properties in the framework. The second version does not include the android: prefix and is for older versions of the platform, on which the system uses the style property from the support library. The effect for each is the same.
In your manifest file, you can apply the theme to your entire app:
Or to individual activities:
Caution: Be certain that each theme and style declares a parent theme in the <style> tag, from which it inherits all styles not explicitly declared by your theme. When modifying the action bar, using a parent theme is important so that you can simply override the action bar styles you want to change without re-implementing the styles you want to leave alone (such as text size or padding in action items).
For more information about using style and theme resources in your application, read Styles and Themes.
Словарь .attheme
Создавая темы для Telegram на Android, Вы найдете некоторые элементы, переменную которых Вы не знаете, или найдёте какие-то переменные, и Вам не понятно, что они меняют. Во встроенном редакторе у переменных нет описания, и это только ухудшает ситуацию. В итоге, Вам приходится спрашивать кого-то, кто знает больше о создании тем.
Мы начали этот словарь, чтобы собрать описания переменных в одном месте. В словаре уже есть описания многих переменных, но ещё больше переменных ещё только предстоит описать. И Вы можете помочь нам с этим!
Каждая часть словаря — свободное ПО. Исходный код этого сайта доступен на GitLab здесь, а самой важной части словаря — базы данных — доступен на GitLab здесь. Вы можете помочь сделать эти части лучше, создавая Merge Requests в репозиториях выше, и как только их примут, Ваши изменения будут сразу видны на этом сайте!
Терминология
В этом разделе содержится список терминов, с которыми рекомендуется ознакомиться, прежде чем начать пользоваться словарём.
Резервная переменная
Резервная переменная — это переменная, которая используется вместо описываемой при выполнении следующих условий:
описываемая переменная отсутствует в файле темы, т.е. для неё установлен цвет по умолчанию;
резервная переменная присутствует в файле темы, т.е. для неё установлен пользовательский цвет.
Например, для dialogShadowLine резервной переменной является chat_emojiPanelShadowLine . Возможны следующие ситуации:
обе переменные отсутствуют в файле темы — для обеих переменных используются цвета из стандартной темы;
dialogShadowLine отсутствует в файле темы, а chat_emojiPanelShadowLine — присутствует. В этом случае первая переменная окрашивается в цвет последней;
dialogShadowLine присутствует в файле темы — цвет обеих переменных определяется как обычно.
windowBackgroundWhite
Задаёт фон практически везде: например, фон списка чатов или настроек.
windowBackgroundGray
Задаёт второстепенный фон: например, фон в настройках между разделами, или фон после истории звонков, если он не занимает весь экран.
Красное — windowBackgroundWhite , зелёное — windowBackgroundGray .
chat_wallpaper
Задает цвет фона чата.
Будьте осторожны: если вы использовали картинку в качестве фона, телеграм будет сжимать ее каждый раз, когда вы меняете любую переменную через редактор тем приложения. Поэтому после всех внесенных изменений установите картинку снова.
Пример фона с картинкой.
Текст
Основной текст
windowBackgroundWhiteBlackText
Задаёт цвет основного текста в приложении.
Будьте внимательны: цвет заголовков в результатах инлайн-бота также устанавливается этой переменной, хотя фон результатов устанавливается chat_messagePanelBackground , а не windowBackgroundWhite . Подумайте о том, чтобы задавать chat_messagePanelBackground и windowBackgroundWhite один и тот же цвет, или проверяйте читабельность результатов бота.
windowBackgroundWhiteGrayIcon
Задаёт цвет иконок у кнопок перехода в другие разделы приложения. Их можно увидеть, например, в Настройках или над списком контактов.
Красное — windowBackgroundWhiteBlackText ,
тёмно-синее — windowBackgroundWhiteGrayIcon .
Серый текст
windowBackgroundWhiteGrayText
Задаёт цвет текста времени последнего входа у контактов/участников группы.
windowBackgroundWhiteGrayText2
текста описаний под названиями в Настройках;
иконок в шапке в общих медиа;
иконки Вернуться назад на экране смены номера телефона.
Будьте внимательны: цвет текста описания в результатах инлайн-бота также устанавливается этой переменной, хотя фон результатов устанавливается chat_messagePanelBackground , а не windowBackgroundWhite . Подумайте о том, чтобы задавать chat_messagePanelBackground и windowBackgroundWhite один и тот же цвет или проверяйте читабельность результатов бота.
windowBackgroundWhiteGrayText3
текста количества участников, информации о файлах и т.д. в результатах поиска в списке чатов;
текста версии приложения внизу экрана Настроек.
Будьте внимательны: цвет имени пользователя у инлайн-ботов и участников чата в окне подсказок также устанавливается этой переменной, хотя фон окна устанавливается chat_messagePanelBackground , а не windowBackgroundWhite . Подумайте о том, чтобы задавать chat_messagePanelBackground и windowBackgroundWhite один и тот же цвет или проверяйте читабельность результатов бота.
windowBackgroundWhiteGrayText4
текста описаний под секциями в Настройках;
столбца букв слева в Контактах, когда установлена сортировка по имени.
windowBackgroundWhiteGrayText6
Задаёт цвет информационного текста на экранах:
смены номера телефона;
установки или смены кода-пароля.
windowBackgroundWhiteGrayText8
Задаёт цвет информационного текста под полем ввода:
при изменении имени пользователя или информации о себе в Настройках;
при создании нового канала.
Красный текст
windowBackgroundWhiteRedText
Задаёт цвет текста красной кнопки «Сбросить настройки автозагрузки» в Настройках → Данные и память.
Примечание: Вы не сможете изменить эту переменную через редактор тем приложения, поэтому используйте .attheme editor, чтобы изменить цвет.
windowBackgroundWhiteRedText2
Задаёт цвет текста и иконки у красной кнопки «Завершить все другие сеансы» в Настройках → Устройства.
windowBackgroundWhiteRedText3
Задаёт цвет текста и нижней границы при неправильном вводе данных в Telegram Passport.
windowBackgroundWhiteRedText4
Задаёт цвет текста при неправильном вводе имени пользователя, когда оно не соответствует требованиям или уже занято.
windowBackgroundWhiteRedText5
Задаёт цвет текста красной кнопки «Удалить все исключения» в Настройках → Уведомления и звуки → Уведомления из чатов (любой раздел).
Красное — windowBackgroundWhiteRedText ,
тёмно-синее — windowBackgroundWhiteRedText2 ,
зелёное — windowBackgroundWhiteRedText3 ,
фиолетовое — windowBackgroundWhiteRedText4 ,
светло-синее — windowBackgroundWhiteRedText5 .
Зеленый текст
windowBackgroundWhiteGreenText
Задаёт цвет текста при правильном вводе имени пользователя, когда оно соответствует требованиям и не занято.
windowBackgroundWhiteGreenText2
Задаёт цвет текста прироста в статистике канала в секции «Общая».
Красное — windowBackgroundWhiteGreenText ,
тёмно-синее — windowBackgroundWhiteGreenText2 .
Синий текст
windowBackgroundWhiteBlueText
текста кнопки «ещё», раскрывающей полный текст описания в группах и каналах;
текста «в сети» у контактов/участников группы.
windowBackgroundWhiteBlueText2
текста кнопки «Присоединиться» под описанием канала;
текста кнопки «Создать новую папку» в Настройках → Папки.
windowBackgroundWhiteBlueText3
Задаёт цвет текста «в сети» в результатах поиска в списке чатов.
windowBackgroundWhiteBlueText4
текста и иконки у кнопок изменения фона и темы в Настройках → Настройки темы;
текста подходящих результатов поиска.
windowBackgroundWhiteBlueText5
Задаёт цвет текста кнопки «Задать пароль» в Telegram Passport, когда отключена двухэтапная аутентификация.
windowBackgroundWhiteBlueText6
Задаёт цвет текста пинга подключенного прокси.
Красное — windowBackgroundWhiteBlueText ,
фиолетовое — windowBackgroundWhiteBlueText2 ,
тёмно-синее — windowBackgroundWhiteBlueText3 ,
светло-синее — windowBackgroundWhiteBlueText4 ,
зелёное — windowBackgroundWhiteBlueText5 ,
жёлтое — windowBackgroundWhiteBlueText6 .
windowBackgroundWhiteBlueHeader
Задаёт цвет заголовков в Настройках.
windowBackgroundWhiteValueText
Задаёт цвет текста выбранных опций и значений в Настройках.
windowBackgroundWhiteBlueButton
Задаёт цвет текста кнопок:
«Добавить исключение» в Настройках → Уведомления и звуки → Уведомления из чатов (любой раздел);
«Добавить участника» под описанием группы.
windowBackgroundWhiteBlueIcon
Задаёт цвет иконки у кнопок:
«Добавить исключение» в Настройках → Уведомления и звуки → Уведомления из чатов (любой раздел);
«Добавить участника» под описанием группы.
windowBackgroundWhiteLinkText
текста ссылок в общих медиа и описании канала;
текста ссылок вида @username и t.me/username в профиле и описании группы.
windowBackgroundWhiteLinkSelection
Задаёт цвет эффекта нажатия на ссылку в общих медиа.
Оранжевое — windowBackgroundWhiteBlueHeader ,
светло-синее — windowBackgroundWhiteValueText ,
фиолетовое — windowBackgroundWhiteBlueButton ,
тёмно-синее — windowBackgroundWhiteBlueIcon ,
коричневое — windowBackgroundWhiteLinkText ,
жёлтое — windowBackgroundWhiteLinkSelection .
Элементы управления
Текстовое поле ввода
Можно найти, нажав на плавающую кнопку «Добавить контакт» в нижнем правому углу в Контактах.
Примечание: цвет вводимого текста задаётся windowBackgroundWhiteBlackText .
windowBackgroundWhiteHintText
Задаёт цвет текста подсказки ввода.
windowBackgroundWhiteInputField
Задаёт цвет нижней границы у неактивного поля ввода.
windowBackgroundWhiteInputFieldActivated
Задаёт цвет нижней границы у активного поля ввода.
Красное — windowBackgroundWhiteHintText ,
тёмно-синее — windowBackgroundWhiteInputField ,
зелёное — windowBackgroundWhiteInputFieldActivated .
Выбор элемента из списка
Можно найти, нажав на плавающую кнопку «Добавить контакт» в нижнем правому углу в Контактах.
windowBackgroundGrayLine
Задаёт цвет нижней границы элемента, выбранного из списка.
Фиолетовое — windowBackgroundGrayLine .
Переключатели
switchTrack
Задаёт цвет неактивного переключателя в Настройках.
switchTrackChecked
Задаёт цвет активного переключателя в Настройках.
switch2Track
Задаёт цвет неактивного переключателя на экране изменения возможностей участников группы или администратора. Если Вы не можете предоставить какую-либо возможность, переключатель будет иметь более бледный цвет, чем тот, который Вы выбрали.
switch2TrackChecked
активного переключателя на экране изменения возможностей участников группы или администратора. Если Вы не можете отозвать какую-либо возможность, переключатель будет иметь более бледный цвет, чем тот, который Вы выбрали;
иконки QR-кода в профиле справа от публичной ссылки.
Панель с глобальным переключателем
Можно найти в Настройках → Данные и память → Автозагрузка медиа (любой раздел).
windowBackgroundUnchecked
Задаёт цвет фона неактивной панели.
windowBackgroundChecked
Задаёт цвет фона активной панели.
windowBackgroundCheckText
Задаёт цвет текста на панели.
Красное — windowBackgroundUnchecked ,
фиолетовое — windowBackgroundChecked ,
жёлтое — windowBackgroundCheckText .
switchTrackBlue
Задаёт цвет неактивного глобального переключателя.
switchTrackBlueThumb
Задаёт цвет кружка внутри неактивного глобального переключателя.
switchTrackBlueSelector
Задаёт цвет эффекта нажатия на неактивный глобальный переключатель.
switchTrackBlueChecked
Задаёт цвет активного глобального переключателя.
switchTrackBlueThumbChecked
Задаёт цвет кружка внутри активного глобального переключателя.
switchTrackBlueSelectorChecked
Задаёт цвет эффекта нажатия на активный глобальный переключатель.
Фиолетовое — switchTrackBlue ,
красное — switchTrackBlueThumb ,
тёмно-синее — switchTrackBlueSelector ,
жёлтое — switchTrackBlueChecked ,
светло-оранжевое — switchTrackBlueThumbChecked ,
светло-зелёное — switchTrackBlueSelectorChecked .
Радиокнопки
Примечание: если Вы используете редактор тем приложения, следующие переменные можно изменить, перейдя в Настройки → Настройки чатов.
radioBackground
Задаёт цвет неактивной радиокнопки в Настройках → Язык и во всплывающих диалоговых окнах.
radioBackgroundChecked
активной радиокнопки в Настройках → Язык;
галки в Настройках → Стикеры и эмодзи → Быстрая реакция;
галки в выпадающем меню в общих медиа.
Круглые чекбоксы
checkboxDisabled
Задаёт цвет неактивного чекбокса в Настройках → Язык → Не переводить (нужно включить функцию «Показать кнопку «Перевести»»).
Примечание: если Вы используете редактор тем приложения, эту переменную можно изменить, нажав на плавающую кнопку снизу справа в списке чатов и выбрав «Создать группу».
checkbox
Задаёт цвет фона активного чекбокса у выбранных чатов/сообщений.
checkboxCheck
галки внутри активного чекбокса у выбранных чатов/сообщений;
неактивного чекбокса у остальных сообщений.
Будьте внимательны: эта переменная также задаёт цвет:
иконки «+» внутри кружка у кнопки «Создать новую папку» в Настройках → Папки, хотя цвет фона кружка устанавливается switchTrackChecked , а не checkbox ;
галки внутри активного чекбокса в Настройках → Язык → Не переводить, хотя цвет фона чекбокса устанавливается radioBackgroundChecked , а не checkbox ;
галки внутри цветных чекбоксов в Настройках → Данные и память → Использование памяти → Очистить кэш Telegram. Фон этих чекбоксов устанавливается следующими переменными: