- Урок 19. Как создать андроид-приложение с вкладками – TabLayout с ViewPager2 на Kotlin
- Добавление TabLayout в макет разметки экрана
- Реализация вкладок в MainActivity
- Android working with ViewPager2, TabLayout and Page Transformers
- Whats’s New in ViewPager2
- 1. ViewPager with Static Views
- 2. ViewPager with Tabs & Fragments
- 3. ViewPager2 Orientation
- 4. ViewPager Transformers
- Android ViewPager2 with TabLayout
- Introduction
- Prerequisites
- Step 1 — Creating an Android Project
- Step 2 — Adding Views in Xml Layouts
- Step 3 — Creating ViewPager2 adapter
- Step 4 — Testing the ViewPager2 component
- Step 5 — Integrating TabLayout
- Conclusion
- About the author
- Want to learn more about the EngEd Program?
- Android ViewPager with Tabs
- What is ViewPager?
- Step of implementation ViewPager
- Final Outcome
- Project setup and dependencies
- Update Color Resource File
- Prepare layout for ViewPager with Tabs
- Create FragmentPagerAdapter
- Create fragment that used to display in ViewPager
- Open fragment Java file and paste below code
- Create ViewModel
- Open MainActivity and add below code
- Conclusion
Урок 19. Как создать андроид-приложение с вкладками – TabLayout с ViewPager2 на Kotlin
На прошлом уроке мы познакомились с ViewPager2 и создали андроид-приложение, в котором можно листать экраны свайпом вправо или влево. На этом уроке добавим в верхней части экрана вкладки, которые будут содержать заголовки и индикатор экрана, на котором находится пользователь в данный момент, а также рассмотрим некоторые их свойства и способы оформления.

В этом уроке будем использовать проект из прошлого урока, можно скачать его на странице урока 18 по ссылке вверху.
Добавление TabLayout в макет разметки экрана
Чтобы добавить вкладки на экран, нужно открыть макет разметки и добавить компонент com.google.android.material.tabs.TabLayout в верхней части экрана:
Для корректного размещения нужно изменить компонент ViewPager2 – высоту укажем 0dp. Таким образом, высоту компонента будет регулировать корневой ConstraintLayout по заданным ограничениям. А вместо ограничения app:layout_constraintTop_toTopOf=»parent» поставим app:layout_constraintTop_toBottomOf=»@+id/tab_layout» – чтобы верх компонента ViewPager2 был ограничен не верхней границей родительского компонента, а нижней границей компонента TabLayout.
Рассмотрим подробнее компонент com.google.android.material.tabs.TabLayout. Свойство app:tabMode=»scrollable» обеспечивает размещение в видимой части экрана только нескольких вкладок, остальные будут доступны в процессе прокрутки. Если мы не укажем это свойство, то в видимой части экрана будут одновременно отображаться все вкладки, и при большом их количестве визуальное восприятие будет затруднено.
Свойство app:tabIndicatorColor=»@color/teal_200″ указывает цвет, а app:tabIndicatorHeight=»4dp» – толщину индикатора вкладки.
Далее идут свойства ширины – указываем по родителю – и высоты – указываем по содержимому.
Последние три свойства – ограничения верхней части и боковых сторон компонента по родителю.
Реализация вкладок в MainActivity
Открываем класс MainActivity и пишем реализацию вкладок:
Источник
Android working with ViewPager2, TabLayout and Page Transformers
As we all know, the Android team is constantly releasing new updates and improvements to the Android Framework. One of the components that received major updates is ViewPager2. ViewPager2 is the replacement of ViewPager and got few performance improvements and additional functionalities. In order to use ViewPager2, you should consider using androidx artifacts in your project.
In my earlier tutorial, I have explained Building Intro Sliders to your App using ViewPager. In this article, we are going to try the same but using ViewPager2. We’ll also go through the additional interesting functionalities provided by ViewPager2.
DEMO

Whats’s New in ViewPager2
- ViewPager2 is improvised version of ViewPager that provides additional functionalities and addresses common issues faced in ViewPager.
- ViewPager2 is built on top of RecyclerView. So you will have great advantages that a RecyclerView has. For example, you can take advantage of DiffUtils to efficiently calculate the difference between data sets and update the ViewPager with animations.
- ViewPager2 supports vertical orientation. Earlier vertical swiping is done by customizing the ViewPager.
- ViewPager2 has right-to-left(RTL) support and this will be enabled automatically based on app locale.
- When working with a collection of Fragments, calling notifyDatasetChanged() will update the UI properly when an underlying Fragment changes its UI.
- ViewPager2 supports page transformations i.e you can provide animations when switching between pages. You can also write your own custom page transformation.
- PagerAdapter is replaced by RecyclerView.Adapter as its based on RecyclerView.
- FragmentStatePagerAdapter is replaced by FragmentStateAdapter.
To get started with ViewPager2, add the dependency to app/build.gradle.
1. ViewPager with Static Views
Usually, ViewPager is used to achieve a tabbed view by combining the TabLayout and collection of Fragments. But if you want to have static views without the Fragment class, you can do it using RecyclerView adapter class.
Below is an example of implementing Intro Slides using ViewPager2. The designs are taken from my older example How to Build Intro Slider for your App but the implementation part varies due to changes in ViewPager2 and in adapter class.
Add the ViewPager2 to your layout file. You can see namespace is uses androidx package androidx.viewpager2.widget.ViewPager2.
This creates horizontally swipeable views that are created using static XML layouts. The full code of this example can be found here.
2. ViewPager with Tabs & Fragments
If you want to create swipeable views with Tabs, you can combine ViewPager2, TabLayout and Fragments.
To use TabLayout, add Material Components to your package. This makes the material TabLayout available in your project.
Add TabLayout and ViewPage2 to your layout.
Create required test Fragment classes MoviesFragment, EventsFragment and TicketsFragment.
Finally, create an adapter class that provides Fragments to ViewPager. Here we can see ViewPagerFragmentAdapter extends FragmentStateAdapter.
3. ViewPager2 Orientation
In a few scenarios, you might want to provide vertical swiping instead of traditional horizontal swiping. To enable vertical swiping, add android:orientation to ViewPager2 element.
Vertical orientation can also be enabled programmatically by calling setOrientation() method.
4. ViewPager Transformers
Another great feature of ViewPager2 is, page transformations i.e the page transition animation from one page to another. Traditionally, we see a sliding animation between two screens. This animation can be customized by providing page transformers to ViewPage2.
To set a custom transformation, use setPageTransformer() method. Below example creates Flip animation between pages.
This creates beautiful vertical flip animation when swiping the pages.
Below are a set of ViewPager transitions that I have collected from different sources (All the credits goes to original authors).
Hi there! I am Founder at androidhive and programming enthusiast. My skills includes Android, iOS, PHP, Ruby on Rails and lot more. If you have any idea that you would want me to develop? Let’s talk: [email protected]
Источник
Android ViewPager2 with TabLayout
November 22, 2020
Slide transition between screens is common in Android applications. We can use the navigation components or a swipe-able view to create this transition. A common swipe-able view is ViewPager2 . The ViewPager library has been around for quite a while.
Introduction
This view allows the developer to display views or fragments to the user in a swipe-able format. This feature is common in content display applications and in app setups.
ViewPager2 is often integrated with TabLayout . A TabLayout indicates the current page and allows a user to switch through pages.
ViewPager2 is a newer version of the ViewPager library. A significant difference from the old library is the use of a RecyclerView adapter. With this, views are now recycled. This improves user experience by making smooth transitions and minimizing memory usage.
This article goes through implementing ViewPager2 and TabLayout in an Android application.
Prerequisites
To follow through with this tutorial, you will need to:
- Have Android Studio installed.
- Have a basic knowledge of building Android applications.
- Have a basic understanding of Kotlin programming language.
Let’s get started!
Step 1 — Creating an Android Project
In this step, we’re going to create our application. Open Android Studio and start a new project using the empty activity template. On the next page, give the application a name and keep the default settings.
Click Finish and wait for the project build process to finish.
Step 2 — Adding Views in Xml Layouts
Our activity_main layout file will contain only two views. Add them as follows.
We also need to create a layout that we’ll display on the ViewPager2 component. Go to File -> New -> XML -> Layout XML File to create the layout file. In the layout file, replace the default TextView widget with the one below.
We’re done with the xml files. Let’s go ahead and create an adapter for our ViewPager2 component.
Step 3 — Creating ViewPager2 adapter
As I mentioned earlier, the ViewPager2 component uses a recyclerview adapter. The adapter’s responsibility is to render data to the viewPager2 component. The recyclerview adapter adds vertical scroll ability, which was absent in the old ViewPager . We will show this ability later in the article.
Let’s start creating the adapter.
Go to File -> New -> Kotlin File/Class . Select class and name the file PagerAdapter .
In the adapter class, add the following code.
This adds the constructor and extends the base class RecyclerView.Adapter . The base class takes a typed parameter which is a view holder. The PagerAdapter.PageHolder class is a view holder class that we are yet to create.
Inside the PagerAdapter class, add the PageHolder class as an inner class.
The class needs to extend the base class RecyclerView.ViewHolder . It should also pass in the view it gets as a parameter. A ViewHolder , as the name suggests, is a class that holds and describe views that each list item should contain. We create our view references in this class.
Let’s add our view’s reference to the view holder.
Now override the members of the RecyclerView.Adapter class. We only need to override these three members.
Read this article for a deeper explanation of the methods.
Add the implementation to the methods as shown below.
In the onCreateViewHolder method, we inflate the page_layout layout using a LayoutInflater . In the onBindViewHolder method, we assign a word from the word list to the TextView . The getItemCount is a method where we return the size of the word list.
That’s all for the adapter.
Step 4 — Testing the ViewPager2 component
Open MainActivity.kt file. In the onCreate method, add a list of words.
Then add the adapter as shown.
That’s what we need for the ViewPager2 . Now build and run the application.
The output should look like this.
To change the scroll orientation to vertical, add the following statement in the onCreate method.
It should resemble the demo below.
Step 5 — Integrating TabLayout
Now that our view pager is functioning as expected. Let’s go ahead and integrate it with TabLayout .
To integrate ViewPager2 with TabLayout we need to use a TabLayoutMediator class. This was easier with the old ViewPager. We had to use the TabLayout ‘s setUpWithViewPager method and pass the ViewPager2 reference.
The TabLayoutMediator class takes in two parameters, the TabLayout and ViewPager2 references.
The class then takes a lambda function with two parameters. TabLayout.Tab and an integer representing the position of the ViewPagers’ pages.
In the function, we set the tabs’ text to the position plus one. We add one because the positions start from zero. We attach the components by calling the attach method.
Build and run the application. This is how it should look.
Another essential feature of TabLayout is the onTabSelectedListener . This notifies the listeners whenever a tab’s selected, unselected, or reselected. This is useful when one wants to perform some background tasks when the listener fires up. We’ll use toasts in our application for demonstration.
Add the following code to implement the feature.
Build and rerun the app.
Conclusion
In this article, we have gone through creating the ViewPager2 component. We have also seen how we can integrate it with a TabLayout. This is a common UI component, and almost all apps that display data in page format use it.
Achieving the slide transition between content screens is relatively easy with the component. You don’t need to implement gesture listeners since the component does that for you. You can find the app’s source code on Github.
Peer Review Contributions by: Linus Muema
About the author
Peter Kayere is an undergraduate student at Jomo Kenyatta University of Agriculture and Technology studying Computer Technology. Peter has a great passion in software development particularly mobile web and android application development. Peter’s most used programming languages are Kotlin and Javascript.
Want to learn more about the EngEd Program?
Discover Section’s community-generated pool of resources from the next generation of engineers.
Источник
Android ViewPager with Tabs
Welcome guys, I help you build a better app, In this post, we’ll learn step by step implementation of Android ViewPager with Tabs layout. Let’s get to work
What is ViewPager?
ViewPager is controlled action swiping between different pages of content. ViewPager gets content from adapter class. These are listed below
PagerAdapter
It’s base class of adapter that provides a generic view for each page to ViewPager.
FragmentPagerAdapter
It fragment represents each page as Fragment. FragmentPagerAdapter keeps each fragment that created in memory. That why its very fast in switch already loaded tab. It the best for use while you using tabs. When you have a large number of fragments then it memory expensive. For solving this problem we used FragmentStatePagerAdapter.
FragmentStatePagerAdapter
It solves the FragmentPagerAdapter problem. It destroys and recreates the fragment as needed only saving state.
In this ViewPager tutorial, we’ll use FragmentPagerAdapter. How to do that let’s see.
Step of implementation ViewPager
- Project setup and dependencies
- Prepare activity layout
- Create Fragment
- Create a subclass of FragmentPagerAdapter and override below methods
- getItem()
- getPageTitle()
- getCount
- Open Activity and set ViewPager on TabLayout
Final Outcome
Project setup and dependencies
Let’s move to Android Studio. Now open app build.gradle and add material io dependency
Update Color Resource File
Open the color.xml file in res=>value folder and add below line of code
Prepare layout for ViewPager with Tabs
Before moving the logic part, let’s prepare XML layout. Open the activity layout file and paste below code.
Create FragmentPagerAdapter
In the src folder, create a subclass of FragmentPagerAdapter named is TabsPagerAdapter. That returns a fragment corresponding to one of the sections/tabs/pages.
For FragmentPagerAdapter implementation, you must override the following method
- getItem() – In case of FragmentPagerAdapter you need to implement getItem() which returns the fragments associated with each position. See the below code here we have returns SpeedDialFragment, RecentsFragment, ContactsFragment
- getPageTitle() – It’s return string title for describing each pages.
- getCount() – Need this method to return of number of pages you have
Create fragment that used to display in ViewPager
In this example, we’ll need three fragments, The name of these fragments is SpeedDialFragment, RecentsFragment, ContactsFragment. For demo, I’m creating a single fragment rest fragment you just replicate the first one.
I’m creating only SpeedDialFragment
Create a new fragment named is SpeedDialFragment. Now open layout file of this fragment and paste below code.
Open fragment Java file and paste below code
Similarly, you have to create RecentsFragment, ContactsFragment as well
Create ViewModel
In src folder create a ViewPager for implementing MVVM. Google recommends ViewModel for communicating to fragment.
Open MainActivity and add below code
Now all logic stuff is done. Now open the MainActivity file and bind the ViewPager and Tabs layout. Finally set the ViewPager on tab layout.
Conclusion
Now build the application and run project. You see your app up and run.
Источник