Adding tabs in android

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

Читайте также:  2 din android для авто

Внутри класса 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, но не получается нигде изменить значение количества вкладок, которое задано по умолчанию.

Источник

How to create Tabs in Android using Kotlin

In this tutorial, I’m going to show you how to implement Tabs in your Android app using Kotlin

We’re going to use the new ViewPager, ViewPager2.

This version of ViewPager has some new features, and the way to use it with Tabs is a little bit different.

Adding Dependencies

Go to your app-level build.gradle, and add the following dependencies:

Creating the Tabs Layout

In your Activity’s layout file, add a TabLayout, for the tabs, and a ViewPager2

Creating Tabs ViewPager Adapter

Create a new Kotlin class and name it TabsPagerAdapter

Next, paste the following code inside:

In the createFragment method, we return a fragment for each position.

In the getItemCount method, we use the same number of fragments with the tabs.

Читайте также:  Remove item from recyclerview android

Adding Tabs in Activity

In the Activity’s Kotlin file, customize and set the number of tabs.

Then, create the adapter for the ViewPager2 and enable the left-n-right swipe.

Last, link the TabLayout and the ViewPager2 together, and set the tab titles and icons for each fragment.

Extra: Customizing Tab’s TextView

You can change Tab’s TextView size and font by getting every child view of the TabLayout and editing the TextViews the way you want

If you have any questions, please feel free to leave a comment below

Источник

Adding tabs in android

Proper content organisation in your Android application may be achieved with a wide range of layouts and widgets. Today I’d like to focus on tabs that is what kind of components are dedicated to using tabs in an application, what are the key principles in using them and how to customize their view.

Basic concept

Tabs are the pattern common and simple, it exceeds mobile or web apps design. To avoid overusing it though we need some clarification about its usage.

What is it for?
The key feature is to make a user aware of alternate views and give the ability to frequent switching between them. It may help to organize data sets (music > rock, pop, jazz, swing) or views with similar aspect (music > all, recent, recommended).

What is it NOT for?
Apps with a deep navigation structure or apps with a single core functionality. It might not be easy to classify the application like that, but it won’t fit in most cases.

If we start to design a tab layout, first let’s define some principles that we will follow. It might be important to say it before starting the implementation and keep it in mind.

Each tab should be equally important

Sometimes it might be a little confusing, but try to bring it to the basics. There’s a little example:
Good usage: Horrors, Comedies, Thrillers, Drama
Bad usage: Blog, Store, Contact Us, About

Even if we are going to customize our view, there are some points that we’ll never break. I know you might disagree with some, but in my opinion, these are what keeps the layout clear and understandable for the user. First of all, present tabs as a single row, either horizontal or vertical. Secondly, always highlight a selected tab, so the users know where they are in the app. Thirdly, do not nest the tabs. Fourthly, adjust a tab name or view to its content, so to the photos section lead tab with a name “photos”, not e.g. “recording”.

Keep consistent design of the tabs

It may be problematic in two cases. The one is the size of the tab, which should be similar to each one. You should be avoiding long descriptions in the tab because it is easier to adjust a size of one-word tabs to each other. The second one is if you decide to use something more than text tabs, like with images, for example, you should keep the pattern for each one and do not combine image tabs with text tabs. It brings unnecessary mess.

The concept above should be pretty general and mostly applies not only to Android apps. From now on let’s write some code! And this is going to be very Android-specific!

Default usage

First, for using android.support.design.widget.TabLayout add design support dependency to build.gradle :

Then we can define TabLayout into layout XML. The very basic usage of TabLayout is to use it as any other view container:

Читайте также:  Как снять логи с андроида

Mind that only TabItem instances can be added to TabLayout.

Then, to take some actions when the tab is selected, we have to add a listener to out tab layout:

in onTabSelected method we have an access to the selected tab and all its view elements, like e.g. text. Very useful is especially a position field, which can be used as an index to a different container or as a reference to another view.

Adding tabs programmatically

To add tabs programmatically instead of defining it into xml simply use addTab() method. To add tab with single text simply define it like that:

Custom Tab view

The fun part is to finally add some more interesting view of our tabs instead of using only text. Let’s combine the text with some nice images! Like this:

Define a round background for our image under res/drawable :

Then custom_tab.xml under res/layout

Under drawable again add some images you want to use for your tabs. Let’s say they are dog.png and cat.png . Now adding a neat tab with your custom layout will be as easy as last time.

Little fancy customization

In the end, I’d like to share with you my concept of a TabLayout view, feel free to take some inspiration. Here’s how it’s going to look like:

To achieve that we’ll need to override some TabLayout functionality! This is what we are going to start with:

The simplest change is to make the tab’s text bold when it is selected. We need addOnTabSelectedListener where we can implement the tab’s behavior on selection. Then just apply a typeface as above! In XML definition remove highlight with the following attribute:

First step done.

Center tabs

Next thing we will do is to display tabs with a selected tab in the center. Add this attribute to XML definition:

It will allow tabs to get over the screen. In consequence, selecting different tabs will scroll the whole layout and display selected one in the center if the rest of the tabs fill the remaining part of the screen. That means a few first and a few last tabs won’t be centralized but aligned with the edge of the parent view. But! We can change it! In onLayout method let’s do some math. We will add padding to the first and the last tab, so it is always in the center, and that’s how we could calculate it:

And these are some helper methods:

Resizing

Now the last feature! Let’s make our tabs resize when they away from the center, so we could get the impression they are on the carousel. Define some zoom multiplicators and help array:

Then do some math once again! This time we need to override onDraw method:

While calculating how much to scale the tab, we need to define how far away ( distance ) is our tab from the center ( sliderCenter ). Base on that we choose, scale a multiplicator between MIN_ZOOM and MAX_ZOOM .

That’s it, your sliding tabs are ready to use!

The full code you can find on my github account. It contains even more functionalities with scrolling and docking tabs in the center. Feel free to test it, use it and modify it!

References:

By Radek Pieczątkiewicz, Junior Software Engineer @ Bright Inventions Email

Источник

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