- Android Material Design Tabs (Tab Layout) with Swipe
- Делаем вкладки с помощью TabLayout
- Библиотека Android Support Design
- Создание TabLayout
- Создание фрагментов
- Подключение FragmentPagerAdapter
- Настройка вкладки
- Настройка TabLayout
- Создание стиля для TabLayout
- Добавление иконок в TabLayout
- Добавление иконок и текста в TabLayout
- Добавление пользовательской разметки в TabLayout
- Получение или выбор текущей страницы
- Использование вкладок без фрагментов
- Ещё вариант реализации вкладок
- Делаем вкладки с помощью TabLayout : 3 комментария
- Create a Material Design Tabbed Interface in an Android App
- Prerequisites
- Introduction to the TabLayout Component
- 1. Create an Android Studio Project
- 2. Creating the Fragments (Pages)
- 3. Adding the TabLayout and ViewPager
- 4. Creating the PagerAdapter
- 5. Initialization of Components
- 6. Testing the App
- 7. Scrollable Tabs
- 8. Showing Tab Icons
- 9. Bonus: Using Android Studio Templates
- Conclusion
Android Material Design Tabs (Tab Layout) with Swipe
Jan 16, 2018 · 7 min read
Tab layout are visible below toolbar with View pager, used to create swipeable views on. Tabs are designed to work with fragments. Use them to swipe fragments in view pager. In this article, we are going to show you how to implement material design tabs in your android app.
After creating new project, open build.gradle of app level and add design support library because Tablayout is a part of Android Design Support Library:
Add Tab layout and View pager in you layout activity_main.xml
app_bar.xml for toolbar
Create tab ad a pter which extends to FragmentStatePagerAdapter. Create two list for fragment list and title list. Create method for passing fragment and title that you want to add.
Create Fragments for view pager. We will add fragments in adapter from activity.
Layout for Tab1Fragment fragment_one.xml
Similarly create more fragment that you want to add, Tab2Fragment, Tab3Fragment and so on.. with their layouts.
Define Tab layout and view pager from layout, define adapter, add your fragments with title, set adapter to view pager and tablayout setup with view pager as viewpager swipe with tablayout.
Run this code and you will find below output:
Some options to customize tabs appearance:
app:tabGravity=”fill” for Navigation tab gravity. Other is center for placing navigation tabs from center
app:tabIndicatorColor=”@color/white” for indicator in tabs. Here you can see white indicator.
app:tabIndicatorHeight=”4dp” for indicator height.
app:tabMode=”fixed” for tab mode. Other is scrollable for many more tabs.
app:tabTextColor=”@color/semi_yellow” for unselected tab text color.
app:tabSelectedTextColor=”@color/yellow” for selected tab text color.
If you want to add icons to tab, you have to do is call setIcon() method of tab. Create icon array and assign each one for each tab like this:
If you want to put only icons to tab, modify getPageTitle() method in adapter class as below:
Here you can see there is no more customization after this. For more custom tabs, you have to create custom tabview for navigation tabs manually.
Custom Navigation Tab Layout:
Create custom layout for tab custom_tab.xml
Add below method in your TabAdapter:
Remove below code from your activity:
Add below code in your activity after calling setAdapter() method:
Now if you want to show big text on selected tab or change text color, then you can do this by creating separate method in your adapter like getSelectedTabView() as below:
Modify your DemoActivity.java code as below:
Now same as TextView, add ImageView to tab layout:
Change to your DemoActivity.java code:
Changes to you Tab Adapter class:
Here it is your output for custom navigation tab.
You can change tab text style using typeface, bold, italic, color, text size etc as well as for tab icon.
Источник
Делаем вкладки с помощью TabLayout
Сейчас вкладки лучше всего реализовывать за счёт использования ViewPager с пользовательским «индикатором вкладок» сверху. В этой статье мы будем использовать TabLayout от Google, включенный в библиотеку Android Support Design в Android 6.0 Marshmallow (API 23).
До Android Marshmallow самым простым способом создания вкладок с помощью фрагментов было использование вкладок ActionBar. Однако, все методы, связанные с режимами навигации в классе ActionBar (такие как setNavigationMode(), addTab(), selectTab() и т.д.) на данный момент являются устаревшими.
Библиотека Android Support Design
Перед началом работы с вкладками, нужно добавить необходимую библиотеку. Чтобы добавить библиотеку в свой проект, нужно в файле build.gradle модуля приложения добавить следующую зависимость в блок dependencies.
Создание TabLayout
Просто добавьте android.support.design.widget.TabLayout, который будет использоваться для отображения различных параметров вкладок, в код разметки. Компонент android.support.v4.view.ViewPager будет использоваться для создания страницы, отображающей фрагменты, которые мы создадим далее.
Создание фрагментов
Теперь, когда у нас есть ViewPager и вкладки в разметке, мы можем перейти к определению содержимого каждой из вкладок. Поскольку каждая вкладка представляет собой только фрагмент, нам необходимо создать и определить Fragment, который нужно показать. В зависимости от ваших требований, в вашем приложении может быть один или несколько фрагментов.
В папке res/layout создадим файл fragment_page.xml и определим в нём код разметки, который будет отображаться на экране при выборе определённой вкладки.
Теперь создадим класс PageFragment и определим в нём логику подключения для фрагмента.
Подключение FragmentPagerAdapter
Следующее, что нужно сделать, это реализовать адаптер для вашего ViewPager, который контролирует порядок вкладок, заголовков и связанного с ними контента. Наиболее важными методами для реализации здесь являются getPageTitle(int position), который используется для получения заголовка нужно вкладки, и getItem(int position), который определяет фрагмент для каждой вкладки.
Настройка вкладки
Наконец, нам нужно прикрепить наш ViewPager к SampleFragmentPagerAdapter, а затем настроить вкладки с помощью двух шагов:
- В методе onCreate() активности определим ViewPager и подключим адаптер.
- Установим ViewPager в TabLayout, чтобы подключить пейджер с вкладками.
Посмотрим, что получилось:
Настройка TabLayout
Существует множество атрибутов, которые вы можете использовать для настройки поведения TabLayout, например:
Название | Параметры | Описание |
tabBackground | @drawable/image | Фон, применяемый к вкладкам |
tabGravity | center, fill | Гравитация вкладок |
tabIndicatorColor | @color/blue | Цвет линии индикатора |
tabIndicatorHeight | @dimen/tabh | Высота линии индикатора |
tabMaxWidth | @dimen/tabmaxw | Максимальная ширина вкладки |
tabMode | fixed, scrollable | Выбор режима — фиксированные вкладки или прокручиваемый список |
tabTextColor | @color/blue | Цвет текста на вкладке |
Здесь вы можете посмотреть все атрибуты для TabLayout.
Создание стиля для TabLayout
Как правило, цвет индикатора вкладки устанавливается как accent, определённый в вашей теме Material Design. Вы можете переопределить этот цвет, создав свой собственный стиль в файле res/values/styles.xml и затем применить этот стиль к TabLayout.
Вы можете переопределить этот стиль для TabLayout в коде разметки:
Ниже вы можете увидеть пример ещё одного стиля, который можно задать для TabLayout:
Добавление иконок в TabLayout
В настоящее время класс TabLayout не предоставляет модель, которая позволяет добавлять иконки для вкладок. Однако вы можете вручную добавить иконки после настройки TabLayout.
Внутри класса FragmentPagerAdapter вы можете удалить строку getPageTitle() или просто вернуть null.
После настройки TabLayout в классе активности, вы можете использовать функцию getTabAt() для установки иконки:
Добавление иконок и текста в TabLayout
Другой подход — использовать SpannableString для добавление иконок и текста в TabLayout. Снова перепишем метод getPageTitle().
По умолчанию, вкладка, созданная TabLayout, устанавливает для свойства textAllCaps значение true, что предотвращает визуализацию ImageSpans. Вы можете переопределить это поведение. изменив в styles.xml свойство tabTextAppearance.
Обратите внимание на дополнительные пробелы, которые добавляются перед заголовком вкладки при создании класса SpannableString. Пустое пространство используется для размещения иконки, чтобы название отображалось полностью. В зависимости от того, где вы хотите разместить иконку, вы можете указать начало диапазона и его конец в методе setSpan().
Добавление пользовательской разметки в TabLayout
В некоторых случаях вместо разметки вкладки по умолчанию мы можем использовать собственную разметку для каждой вкладки. Чтобы добиться этого, переберём все вкладки после прикрепления их к ViewPager в коде активности.
Теперь добавим метод getTabView() в класс SampleFragmentPagerAdapter.
Таким образом, можно настроить любую вкладку в адаптере.
Получение или выбор текущей страницы
С последними обновлениями библиотеки Android Suppoty Design вы также можете получить выбранную позицию вкладки, вызвав метод getSelectedTabPosition(). Если вам нужно сохранить или восстановить выбранную позицию вкладки во время поворота экрана или других изменений конфигурации, этот метод полезен для восстановления исходной позиции.
Во-первых, переместите экземпляры tabLayout и viewPager в глобальные переменные класса активности.
Во-вторых, мы можем сохранить и восстановить позицию вкладки, используя методы onSaveInstanceState() и onRestoreInstanceState().
Использование вкладок без фрагментов
В случае, если вы не хотите использовать в своём приложении фрагменты, вы можете воспользоваться классом android.support.v4.view.PagerAdapter, как, например, в нашем приложении «Карточки для детей«.
Здесь вместо фрагментов в ViewPager передаётся адаптер, наследующий от PagerAdapter. Его код можно увидеть ниже.
Установка адаптера аналогична способам выше, просто вызываем метод setAdapter() и передаёт в него экземпляр класса TabAdapter.
Ещё вариант реализации вкладок
Также вы можете создать свои собственные вкладки с помощью шагов ниже. Такой подход используется в нашем приложении «Менеджер паролей для Wi-Fi сетей«.
Для этого в разметке нужно использовать компоненты TabHost и TabWidget. Внутри с помощью FrameLayout мы задаём, какой контент будет отображаться на экране.
Затем в коде активности добавим следующий код для определения этих компонент и настройки вкладок.
В этом случае переключать вкладки можно легко с помощью метода у TabHost setCurrentTab(int position).
Делаем вкладки с помощью TabLayout : 3 комментария
Я создал ретрофит запрос, получил данные и хочу установить количество вкладок соответственно количеству полученных строк. Куда в адаптере мне вставить этот код? Я создал AsyncTask, но не получается нигде изменить значение количества вкладок, которое задано по умолчанию.
Источник
Create a Material Design Tabbed Interface in an Android App
The material design team at Google simply defines the functionality of tabs in Android as follows:
Tabs make it easy to explore and switch between different views.
In this post you’ll learn how to display tabs using the TabLayout and ViewPager API. In this practical tutorial, we’ll cover the following:
- The TabLayout and ViewPager components.
- The different tab modes: scrollable and fixed.
- How to display icons instead of text for the tab titles.
- For a bonus, you’ll also learn how to use the Android Studio templates feature to quickly bootstrap your project with a tabbed interface.
A sample project for this tutorial can be found on our GitHub repo so you can easily follow along.
Prerequisites
To be able to follow this tutorial, you’ll need:
You can also learn all the ins and outs of the Kotlin language in my Kotlin From Scratch series.
Introduction to the TabLayout Component
TabLayout provides a horizontal layout to display tabs.
The TabLayout component is one of the components introduced as part of the material design artifacts. Moreover, it is also included in the design support library. In a TabLayout , when a tab is selected or tapped, a different page (or fragment) is shown to the user.
The TabLayout component can have its displayed tabs function in one of two ways: fixed and scrollable. If the tabs are fixed, all of the tabs will be displayed on the screen at the same time.
The screenshot below is the latest official WhatsApp Android app (as of this writing), which uses a TabLayout with a fixed mode configuration.
In scrollable tabs, if the number of tabs becomes too wide for the screen, the user can swipe left or right to view more tabs.
Here is an example of a TabLayout with scrollable tab mode—showcased in the latest version of the News & Weather Android app by Google.
Furthermore, the information displayed on a tab can be text, an icon, or a combination of both text and an icon. For example, the latest Twitter app for Android uses icons instead of text on each tab.
In the following sections, we’ll dive into coding a simple app that makes use of TabLayout with a ViewPager . Let’s get rolling!
Design is not just what it looks like and feels like. Design is how it works. — Steve Jobs
1. Create an Android Studio Project
Fire up Android Studio 3 and create a new project (you can name it TabLayoutDemo ) with an empty activity called MainActivity .
2. Creating the Fragments (Pages)
We’re going to create a TabLayout with just three tabs. When each of the tabs is selected, it displays a different Android fragment or page. So let’s now create the three Android fragments for each of the tabs. We’ll start with the first fragment class, and you should follow a similar process for the remaining two fragment classes—FragmentTwo.kt and FragmentThree.kt.
Here is my FragmentOne.kt:
Here is also my R.layout.fragment_one :
3. Adding the TabLayout and ViewPager
To begin using TabLayout and ViewPager in your project, make sure you import the design support and also the Android support artifact—so add these to your module’s build.gradle file to import them.
Also, visit your res/layout/activlty_main.xml file to include both the TabLayout widget and the ViewPager view.
Here we created a simple TabLayout with id tab_layout . In our TabLayout XML widget, you can see that we included some attributes—such as app:tabMode to be fixed and also app:tabGravity to be fill . The app:tabGravity property is used to configure how the tab items will be displayed so as to take up the available space. We set this to fill , which will distribute the items evenly across the width of the TabLayout . Note that this will be more visible in wider displays, such as tablets.
I also included a custom style attribute ( @style/CustomTabLayout ) in our TabLayout widget.
We begin customising our TabLayout by setting the values of the attributes to be applied on the TabLayout . Here are the details for some of the attributes applied:
- tabIndicatorColor : sets the tab indicator’s color for the currently selected tab. This can also be set programmatically by calling setSelectedTabIndicatorColor() on a TabLayout instance.
- tabIndicatorHeight : sets the tab indicator’s height for the currently selected tab. This can be also be set programmatically by calling the setSelectedTabIndicatorHeight() on a TabLayout instance.
- tabSelectedTextColor : sets the text colors for the different states (normal, selected) used for the tabs. The equivalent of this attribute in Java is setTabTextColors() .
Immediately after creating our TabLayout widget in XML, the next view was a ViewPager . The official documentation says the following about ViewPager :
Layout manager that allows the user to flip left and right through pages of data.
4. Creating the PagerAdapter
We need to create a subclass in SampleAdapter.kt that extends the FragmentPagerAdapter . This class is responsible for managing the different fragments that will be displayed on the tabs.
Here we override three methods from the parent class: getItem() , getCount() , and getPageTitle() . Here are the explanations for the methods:
- getItem() : returns a Fragment for a particular position within the ViewPager .
- getCount() : indicates how many pages will be in the ViewPager .
- getPageTitle() : this method is called by the ViewPager to obtain a title string to describe the specified tab.
For example, if the selected tab is the first tab with title «Tab 1 Item» , a FragmentOne page will be shown to the user immediately.
5. Initialization of Components
Next, we are going to initialize instances of our TabLayout , ViewPager , and SampleAdapter . Initialization is going to happen inside onCreate() in MainActivity.kt.
We got references to our TabLayout and ViewPager from R.layout.activity_main and initialized them. We also created an instance of our SampleAdapter —passing an instance of FragmentManager as an argument. We need to supply the views for our ViewPager , so we called setAdapter() and passed in our created adapter to it. Finally, we called setupWithViewPager() on an instance of TabLayout to do some work:
- creation of the required tab for every page
- setting up the required listeners
When the user taps on a tab, it changes the pages in the ViewPager and shows the required page (or Fragment ). Also, swiping between pages updates the selected tab. In other words, this method helps us take care of scroll state change and clicks on the tabs.
The onTabSelectedListener() is used to include a listener that will be invoked when tab selection changes. We’ve overridden the following callbacks:
- onTabSelected() : triggered when a tab enters the selected state.
- onTabUnselected() : invoked when a tab exits the selected state.
- onTabReselected() : invoked when a tab that is already selected is chosen again by the user.
Note that we can also set the tab mode programmatically—instead of via the layout XML—using setTabMode() on an instance of TabLayout . We pass the mode (fixed or scrollable) to this method as arguments. For example, we can pass TabLayout.MODE_FIXED for a fixed mode—or TabLayout.MODE_SCROLLABLE for a scrollable mode.
Note that if you want to explicitly create the tabs instead of using the helper method setUpWithViewPager() , you can instead use newTab() on a TabLayout instance.
Note also that we could explicitly create the tabs via XML instead of programmatically.
6. Testing the App
Finally, you can run the app!
Try interacting with the application by swiping left or right and tapping the tabs.
7. Scrollable Tabs
The official material design guidelines on tabs says the following about scrollable tabs:
Scrollable tabs display a subset of tabs at any given moment. They can contain longer tab labels and a larger number of tabs than fixed tabs. Scrollable tabs are best used for browsing contexts in touch interfaces when users don’t need to directly compare the tab labels.
Let’s see how to create tabs with scrollable mode configuration. I made the title for each of the tabs longer than before. Here is the result in fixed mode:
You can see that TabLayout has used multiple lines to display each of the tab’s titles. In some situations, it will even truncate the titles! This creates a bad user experience, so if your tab titles need to be very long, you should consider using scrollable mode. Note also that if you are going to have more than four tabs, it’s recommended to make the tab mode scrollable.
Let’s change the app:tabMode property from fixed to scrollable .
Remember, you can also set the tab mode programmatically, as discussed earlier.
8. Showing Tab Icons
Let’s now dive into how to replace the tab item text with icons instead.
Here we called the getTabAt() on an instance of TabLayout . Calling this method will return the tab at the specified index. Next, we call setIcon() . Calling this method will set the icon displayed on this tab.
I also set the tab mode to be fixed.
I still override the getPageTitle() inside the SampleAdapter .
Here is the result:
Now, if you want only the icons, you simply don’t override getPageTitle() .
9. Bonus: Using Android Studio Templates
Instead of writing so much code just to create a tabbed interface or activity from scratch, Android Studio 3.0 has some pre-existing code templates (available in Java and Kotlin) to help kick-start your project. One such template can be used to create a tabbed activity.
I’ll show you how to use this handy feature in Android Studio 3.
For a new project, fire up Android Studio 3.
Enter the application name and click the Next button.
You can leave the defaults as they are in the Target Android Devices dialog. Click the Next button again.
In the Add an Activity to Mobile dialog, scroll down and select Tabbed Activity. Click the Next button after that.
In the last dialog, scroll down to the Navigation Style drop-down menu and select Action Bar Tabs (with ViewPager). Finally, click the Finish button to accept all configurations.
Android Studio has now helped us to create a project with a tabbed activity. Really cool!
You are strongly advised to explore the code generated.
In an already existing Android Studio project, to use this template, simply go to File > Activity > Tabbed Activity. And follow the similar steps that were described previously.
The templates that come included with Android Studio are good for simple layouts and making basic apps, but if you want to kick-start your app even further, you might consider some of the app templates available from Envato Market.
They’re a huge time saver for experienced developers, helping them to cut through the slog of creating an app from scratch and focus their talents instead on the unique and customised parts of creating a new app.
Conclusion
In this tutorial, you learned how to create a tabbed interface in Android using the TabLayout and ViewPager API from scratch. We also explored how to easily and quickly use the Android Studio templates to create a tabbed interface.
I highly recommend checking out the official material design guidelines for tabs to learn more about how to properly design and use tabs in Android.
To learn more about coding for Android, check out some of our other courses and tutorials here on Envato Tuts+!
Источник