Android tablayout select tab

Делаем вкладки с помощью 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().

Читайте также:  A107f прошивка андроид 10

Использование вкладок без фрагментов

В случае, если вы не хотите использовать в своём приложении фрагменты, вы можете воспользоваться классом android.support.v4.view.PagerAdapter, как, например, в нашем приложении «Карточки для детей«.

Здесь вместо фрагментов в ViewPager передаётся адаптер, наследующий от PagerAdapter. Его код можно увидеть ниже.

Установка адаптера аналогична способам выше, просто вызываем метод setAdapter() и передаёт в него экземпляр класса TabAdapter.

Ещё вариант реализации вкладок

Также вы можете создать свои собственные вкладки с помощью шагов ниже. Такой подход используется в нашем приложении «Менеджер паролей для Wi-Fi сетей«.

Для этого в разметке нужно использовать компоненты TabHost и TabWidget. Внутри с помощью FrameLayout мы задаём, какой контент будет отображаться на экране.

Затем в коде активности добавим следующий код для определения этих компонент и настройки вкладок.

В этом случае переключать вкладки можно легко с помощью метода у TabHost setCurrentTab(int position).

Делаем вкладки с помощью TabLayout : 3 комментария

Я создал ретрофит запрос, получил данные и хочу установить количество вкладок соответственно количеству полученных строк. Куда в адаптере мне вставить этот код? Я создал AsyncTask, но не получается нигде изменить значение количества вкладок, которое задано по умолчанию.

Источник

TabLayout Tutorial With Example In Android Studio

In Android TabLayout is a new element introduced in Design Support library. It provides horizontal layout to display tabs on the screen. We can display more screens in a single screen using tabs. We can quickly swipe between the tabs. TabLayout is basically view class required to be added into our layout(xml) for creating Sliding Tabs. We use different methods of TabLayout to create, add and manage the tabs.

Special Note: TabLayout is used to display tabs on the screen. We can create sliding as well as non sliding tabs by using TabLayout. If we need simple tabs without sliding then we replace the layout with the fragment on tab selected listener event and if we need sliding tabs then we use Viewpager.

Table Of Contents

Basic TabLayout XML Code:

Important Methods Of TabLayout:

Let’s we discuss some important methods of TabLayout that may be called in order to manage the TabLayout.

1. newTab(): This method is used to create and return a new TabLayout.Tab.

Below we create a new tab and set the text and icon for the tab.

2. addTab(Tab tab): This method is used to add a tab in the TabLayout. By using this method we add the tab which we created using newTab() method in the TabLayout. The tab will be added at the end of the list and If it is the first tab to be added then it will become the selected tab.

Below we firstly create a new tab and then add it in the TabLayout.

3. addTab(Tab tab, boolean setSelected): This method is used to add a tab in the TabLayout and set the state for the tab. By using this method we add the tab which we created using newTab() method in the TabLayout. In this method we also set the state of the tab whether it is selected or not.

Below we firstly create a new tab and then add it in the TabLayout and set the true value for setSelected parameter that makes it selectable.

4. addTab(Tab tab, int position): This method is used to add a tab in the TabLayout and set the state for the tab. By using this method we add the tab which we created using newTab() method in the TabLayout. The tab will be inserted at the given position. If it is the first tab to be added then it will become the selected tab.

Below we firstly create a new tab and then add it in the TabLayout at a specific position.

5. addTab(Tab tab, int position, boolean setSelected): This method is used to add a tab at a specific position and set the state of the tab. By using this method we add the tab which we created using newTab() method in the TabLayout. The tab will be inserted at the defined position and a Boolean value used to set the state of the tab. True value is used to make the tab selectable.

Below we firstly create a tab and then add it in the TabLayout at a specific position and we also set true value to make the tab selectable.

6. getSelectedTabPosition(): This method is used to get the position of the current selected tab. This method returns an int type value for the position of the selected tab. It returns -1 if there isn’t a selected tab.

Below we get the current selected tab position.

7. getTabAt(int index): This method is used to get the tab at the specified index. This method returns TabLayout.Tab.

Below we get the tab at 1th index.

8. getTabCount(): This method is used to get the number of tabs currently registered with the action bar. This method returns an int type value for the number of total tabs.

Читайте также:  Как обмануть геолокацию андроид

Below we get the total number of tabs currently registered with the action bar.

9. setTabGravity(int gravity): This method is used to set the gravity to use when laying out the tabs.

Below we set the gravity for the tabs.

10. getTabGravity(): This method is used to get the current gravity used for laying out tabs. This method returns the gravity which we set using setTabGravity(int gravity) method.

Below we firstly set the gravity and then get the current gravity used for laying out tabs.

11. setTabMode(int mode): This method is used to set the behavior mode for the Tabs in this layout. The valid input options are:

MODE_FIXED: Fixed tabs display all tabs concurrently and are best used with content that benefits from quick pivots between tabs.

MODE_SCROLLABLE: Scrollable tabs display a subset of tabs at any given moment and it can contain longer tab labels and a larger number of tabs. They are best used for browsing contexts in touch interfaces when users don’t need to directly compare the tab labels. This mode is commonly used with a ViewPager.

Below we set the behaviour mode for the tabs.

12. getTabMode(): This method is used to get the current mode of TabLayout. This method returns an int type value which we set using setTabMode(int mode) method.

Below we firstly set the tab mode and then get the current mode of the TabLayout.

13. setTabTextColors(int normalColor, int selectedColor): This method is used to set the text colors for the different states (normal, selected) of the tabs.

Below we set the tab text colors for the both states of the tab.

14. getTabTextColors(): This method is used to get the text colors for the different states (normal, selected) of the tabs. This method returns the text color which we set using setTabTextColors(int normalColor, int selectedColor) method.

Below we firstly set the text colors and then get the text colors for the both states of the tab.

15. removeAllTabs(): This method is used to remove all tabs from the action bar and deselect the current tab.

Below we remove all the tabs from the action bar and deselect the current tab.

16. setOnTabSelectedListener(OnTabSelectedListener listener): This method is used to add a listener that will be invoked when tab selection changes.

Below we show how to use addOnTabSelectedListener of TabLayout.

17. removeTab(Tab tab): This method is used to remove a tab from the layout. In this method we pass the TabLayout.Tab object to remove the tab from the layout. If the removed tab was selected then it will be automatically deselected and another tab will be selected if present in the TabLayout.

Below we firstly create and add a tab and then remove it from the TabLayout.

18. removeTabAt(int position): This method is used to remove a tab from the layout. In this method we pass the position of the tab that we want to remove from the layout. If the removed tab was selected then it will be automatically deselected and another tab will be selected if present in the TabLayout.

Below we remove the tab from a specified position of TabLayout.

19. setSelectedTabIndicatorColor(int color): This method is used to set the tab indicator’s color for the currently selected tab.

Below we set the red color for the selected tab indicator.

20. setSelectedTabIndicatorHeight(int height): This method is used to set the tab indicator’s height for the currently selected tab.

Below we set the height for the selected tab’s indicator.

21. setupWithViewPager(ViewPager viewPager): This method is used for setting up the TabLayout with ViewPager. ViewPager is mainly used for creating Sliding tabs.

Below we set the TabLayout with the ViewPager.

Attributes of TabLayout:

Now let’s we discuss some common attributes of a TabLayout that helps us to configure it in our layout (xml).

1. id: id attribute is used to uniquely identify a TabLayout.

2. support.design:tabBackground: This attribute is used to set the background of the tabs. We can set a color or drawable in the background of tabs.

Below we set the Black color for the background of the tabs.

3. support.design:tabGravity: This attribute is used to set the gravity to use when laying out the tabs. We can also set gravity programmatically means in java class using setTabGravity(int gravity) method.

Below we set the gravity for the tabs.

4. support.design:tabIndicatorColor: This attribute is used to set the Color of the indicator used to show the currently selected tab. We can also set color programmatically means in java class using setSelectedTabIndicatorColor(int color) method.

Below we set the red color for the selected tab indicator

5. support.design:tabIndicatorHeight: This attribute is used to set the height of the indicator used to show the currently selected tab. We can also set height programmatically means in java class using setSelectedTabIndicatorHeight(int height) method.

Читайте также:  Как картинку с айфона передать андроид тв

Below we set the height for the selected tab’s indicator.

6. support.design:tabMaxWidth: This attribute is used to set the maximum width for the tabs.

Below we set the maximum width value for the tabs.

7. support.design:tabMinWidth: This attribute is used to set the minimum width for the tabs.

Below we set the minimum width value for the tabs.

8. support.design:tabMode: This attribute is used to set the behavior mode for the Tabs in this layout. We can also set the mode programmatically means in java class using setTabMode(int mode) method.

Below we set the behaviour mode for the tabs.

9. support.design:tabPadding: This attribute is used to set the padding along all edges of tabs.

android.support.design:tabPaddingBottom: Set padding along the bottom edge of the tabs.

android.support.design:tabPaddingEnd: Set padding along the end edge of the tabs.

android.support.design:tabPaddingStart: Set padding along the start edge of the tabs.

android.support.design:tabPaddingTop: Set padding along the top edge of the tabs.

Below we set the padding along all edges of the tabs.

10. support.design:tabSelectedTextColor: This attribute is used to set the text color to be applied to the currently selected tab. We can also set this programmatically using setTabTextColors(int normalColor, int selectedColor) method.

Below we set the text color for the selected tab.

11. support.design:tabTextColor: This method is used to set the default text color to be applied to tabs. . We can also set this programmatically using setTabTextColors(int normalColor, int selectedColor) method.

Below we set the default text color for the tabs.

TabLayout Example In Android Studio:

Example 1 of TabLayout:

Below is the first example of TabLayout in which we display three non-sliding tabs. In this example we define a TabLayout and a FrameLayout in our xml file. In this example we create and add 3 tabs in the TabLayout with the help of different methods of TabLayout. After that we implement setOnTabSelectedListener event and replace the FrameLayout with the fragment’s according to selected tab.

Step 1: Create a new project and name it TabLayoutExample

Step 2: Open build.gradle and add Design support library dependency.

Step 3: Open res -> layout ->activity_main.xml (or) main.xml and add following code:

In this step we add the code for displaying TabLayout and ViewPager in our xml file.

Step4: Open src -> package -> MainActivity.java

In this step we open MainActivity and add the code for initiate the FrameLayout and TabLayout. After that we create and add 3 tabs in the TabLayout. Finally we implement setOnTabSelectedListener event and replace the FrameLayout with the fragment’s according to selected tab.

Step 5: Now we need 3 fragments and 3 xml layouts for three tabs. 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.

FirstFragment.class

SecondFragment.class

ThirdFragment.class

Step 6: 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 for all the three tabs.

fragment_first.xml

fragment_second.xml

fragment_third.xml

Example 2 of TabLayout Using ViewPager:

Below is the example of TabLayout in which we display sliding tabs with the help of ViewPager. In this example we define a TabLayout and a ViewPager in our xml file. In this example we create and add 3 tabs in the TabLayout with the help of different methods of TabLayout. After that we create a PagerAdapter to set up the TabLayout with ViewPager.

Step 1: Create a new project and name it TabLayoutExample

Step 2: Open build.gradle and add Design support library dependency.

Step 3: Open res -> layout ->activity_main.xml (or) main.xml and add following code:

Step 4: Open src -> package -> MainActivity.java

In this step we open MainActivity and add the code for initiate the ViewPager and TabLayout. After that we create and add 3 tabs in the TabLayout. Finally we set an Adapter named PagerAdapter to set up the TabLayout with ViewPager.

Step 5: Create a new Class named PagerAdapter and extend FragmentStatePagerAdapter in the class. In this step we create a PagerAdapter class and extends FragmentStatePagerAdapter In the class for setting the TabLayout with the ViewPager.

Step 6: Now we need 3 fragments and 3 xml layouts for three tabs. 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.

FirstFragment.class

SecondFragment.class

ThirdFragment.class

Step 7: 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 for all the three tabs.

Источник

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