Android tablayout with viewpager2

Урок 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 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:

  1. Have Android Studio installed.
  2. Have a basic knowledge of building Android applications.
  3. 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.

Читайте также:  Android studio api что это

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.

Читайте также:  Com google android onetimeinitializer что это

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 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.

Читайте также:  The best android emulators on pc

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]

Источник

ViewPager2 with TabLayout in Android

Hey ! Welcome to my page .This article helps you to learn about the implementation of ViewPager2 with Fragments and TabLayout. Let’s get started.

TabLayout enhances you to display tabs horizontally. Well in this case, implementation of the ViewPager2 with TabLayout helps to create views in swipeable format. Incase if you wanna create swipeable views in Tabs, you can combine TabLayout, ViewPager2 and Fragments.

1. Make a project and add dependencies

Firstly ,Open the AndroidStudio and then create a new project.
Give project and package name and select language Kotlin and finish.
Now add the following dependencies to app/build.gradle.

Sync your project for gradle to import all required classes.

2. Adding TabLayout and ViewPager2 to Activity

activity_main.xml :

MainActivity.kt :

3. Create empty or blank fragments

In this app, I made a use of three fragments for previewing views between fragments.
Create three empty fragments with associated layouts so that we can add them to ViewPager2.
You shall go with below names.

  1. PetsFragments.kt
  2. CategoriesFragment.kt
  3. WishlistFragment.kt

Take reference of below empty fragments xml layouts and class with different backgrounds to parent.

PetsFragment.kt :

Now we’re done with fragments but create 2 more empty fragments taking reference to above one. Let’s create a adapter for this to link up all those fragments.

4. Create FragmentStateAdapter

To provide Fragments to ViewPager2 we need an adapter class. Let’s create a class which extends to FragmentStateAdapter.

ParentFragmentPagerAdapter.kt :

Finally, we create the TabLayoutMediator that links ViewPager2 and the TabLayout, it has 3 parameters which needs tabs and viewpager information to update fragment with correct tab.

Back in MainActivity.kt create an instance for adapter we have created and later pass that information to ViewPager2 below this way.

Now let’s make use of object TabLayoutMediator and connect Tabs, Fragments with Viewpager2 with TabConfigurationStrategy.

And this is how your MainActivity should look like after making those changes.

MainActivity.kt :

That’s it, no more code changes required. Similarly test the current state of app by adding more fragments or changing existing one to learn more.

Now run the app and have a look at the preview and you will be able to swipe between different fragments. If not take reference from source code below I have shared. Go with the Design Changes if needed.

That’s it people I hope you found this information useful, thanks for reading.

Источник

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