How to use TabLayout with ViewPager2 in Android –

Development issue/problem:

I want to use the com.google.android.material.tabs.TabLayout component with the new Android ViewPager implementation and the Androidx.viewpager2 widget. However, the setupWithViewPager(…) method provided by TabLayout only supports the older implementation of ViewPager. Is it possible to easily link TabLayout to a ViewPager2 component?

How can I solve this problem?

Solution 1:

You need to use this TabLayoutMediator which emulates tabLayout.setupWithViewPager() and configure ViewPager2 with the tab layout. Otherwise, you need to write your own adapter that combines both sides.

In Kotlin the code will look like this.

TabLayoutMediator(tabLayout, viewPager) { tab, position ->
tab.text = tabTitles [position]
viewPager.setCurrentItem(tab.position, true)
}.attach()

Solution 2:

UPDATE

Select the Create tabbed view with ViewPager2 check box.

Here is the updated answer How to use TabLayout with ViewPager2 on Android

Now we don’t need to create a class from TabLayoutMediator.

Use the following dependencies

com.google.android.material:material:1.1.0-alpha08′
implementing ‘androidx.viewpager2:viewpager2:1.0.0-beta02’.

INTERNATIONAL PREFIX

XMl layout

Activities

import androidx.appcompat.appCompatActivity
import android.os.bundle
import kotlinx.android.synthetic.main.*
import com.google.android.material.tabs.TabLayoutMediator

import com.google.android.material.tabs.TabLayout

Main activity class : AppCompatActivity() {.

fun override onCreate(savedInstanceState: Bundle?) {
super.onCreate(savedInstanceState)
setContentView(R.layout.activity_main)

// setSupportActionBar (toolbar)
viewpager.adapter = AppViewPagerAdapter(supportFragmentManager, lifecycle)

TabLayoutMediator(tabs, viewpager, object: TabLayoutMediator.OnConfigureTabCallback {
override fun onConfigureTab(tab: TabLayout.Tab, position: Int) {
// Design each tab here
tab.text = Tab $position
}
})).attach()

}
}

DETERMINED

If you are using the com.google.android.material:material:1.1.0-alpha10 implementation, use the following code.

TabLayoutMediator(tabs, view page,
TabLayoutMediator.TabConfigurationStrategy { tab, position ->
when (position) {
0 -> { tab.text = TAB ONE}
1 -> { tab.text = TAB TWO}
}
}).attach()

EXIT

Enter a description of the image here

Solution 3:

Initialize the TabLayoutMediator object with a TabLayout object, ViewPager2 , autoRefresh with a boolean type, and the OnConfigurationChangeCallback object.

TabLayoutMediator tabLayoutMediator = new TabLayoutMediator(tabLayout, viewPager2, true, new TabLayoutMediator.OnConfigureTabCallback() {
@Override
public void onConfigureTab(TabLayout.Tab, int position) {
// Position of the flow and this tab
}
})

Finally, just call attach() to the TabLayoutMediator object to attach the tablaout to the viewpager :-.

tabLayoutMediator.attach() ;

autoRefresh – button if set to true – ( is set to true by default)

REQUIRES all tabLayout tabs when theDataSetChanged message is called on the Viewpager adapter.

Use the contents of TabLayoutMediator.java.

Solution 4:

No hacking, no extensions, no TabLayoutMediator

I use the com.google.android.material:material:1.2.0-alpha02 implementation and do the following without using TabLayoutMediator.
Instead, I link TabLayout to ViewPager2 using the method described here. I’ve also included an example of work on Github here. I think I’ve narrowed it down to an example of minimal work. Let me explain the main points.

Adding elements to the model

First we need to add TabLayout and ViewPager2 to the layout. I put them here in LinearLayout and CoordinatorLayout, but of course you can do whatever you want.

Connecting the adapter to the viewfinder

Thus, the adapter is responsible for providing the correct fragments for the activity.
You need to extend the FragmentStateAdapter, which I did simply as shown below (it’s a private lesson as it’s explained here in my MainActivity.java) :

The closed ViewStateAdapter class extends the FragmentStateAdapter {

public ViewStateAdapter(@NonNull fragmentManager fragmentManager, @NonNull lifecycle lifecycle) {
super(fragmentManager, lifecycle);
}

@NonNull
@Override
public Fragment createFragment(int position) {
// Hardcoded in this order, you should use lists and make sure the titles match
if (position == 0) {
return new BarFragment();
}
return new FooFragment();
}

@Override
public int getItemCount() {
// Hardcoded, use lists
return 2;
}
}

I can then connect my own adapter to the ViewPager as shown below:

FragmentManager fm = getSupportFragmentManager();
ViewStateAdapter sa = new ViewStateAdapter(fm, getLifecycle());
last ViewPager2 pa = findViewById(R.id.pager);
pa.setAdapter(sa) ;

I added pieces to my viewpager. (Since I have fragments encoded in my adapter, you need to use a list and something like the addFragment method or something).

Plate

Then, with

TabLayout tabLayout = findViewById(R.id.tabLayout);
tabLayout.addTab(tabLayout.newTab().setText(Bar));
tabLayout.addTab(tabLayout.newTab().setText(Foo))

I add two tabs to the TabLayout that show titles, but don’t let you jump to snippets.

Connecting TabLayout with adapter

tabLayout.addOnTabSelectedListener(new TabLayout.OnTabSelectedListener() {
@Override
public void onTabSelected(TabLayout.Tab)) {
pa.setCurrentItem(tab.getPosition());
}

@Frame
on TabUnselected(TabLayout.Tab tab) {

}

@TabReview(TabLayout.Tab tab) {

}
});

That should be simple enough. The user clicks on the tab, I get the position in my memory, and I just set the current adapter element to this position.

Replacement of the nameplate at replacement of the nameplate at replacement of the nameplate at replacement of the nameplate at replacement of the nameplate

Finally, we go back when the user scrolls through the snippet to find the appropriate bookmark element, such as the

pa.registerOnPageChangeCallback(new ViewPager2.OnPageChangeCallback() {
@Override
public void onPageSelected(int position) {
tabLayout.selectTab(tabLayout.getTabAt(position));
}
})

Solution no. 5:

You can use the Kotlin expansion function:

fun TabLayout.setupWithViewPager(viewPager: ViewPager2, tags: List) {

if (labels.size != viewPager.adapter ?.itemCount)
throw Exception (The list size and the number of tabs must be equal !)

TabLayoutMediator(this, viewPager,TabLayoutMediator.TabStrategyConfigurationStrategy { tab, position ->tab.text = labels [position]}).attach()}).attach()} }

And that’s a good thing:

tabLayout.setupWithViewPager(viewPager, listOf(tab A, tab B))

Solution no. 6:

I ran mine on the com.google.android.material:material:1.2.1 implementation and I didn’t use tabLayoutMediator either. For starters, https://developer.android.com/jetpack/androidx/migrate/class-mappings has changed the tab layout in androidX, so use com.google.android.material.tabs.TabLayout in your import declaration.
The rest of my implementation of the solution:
Xml declaration of the viewPager and TabLayout layout

and an activity file

Override
protected by blank onCreate(Bundle storedInstanceState) {
super.onCreate(storedInstanceState) ;

// Define the content of the activity in the layout file
setContentView(layout.activity_main) ;

// Find the ViewPager that the user can use to browse through fragments
ViewPager viewPager = (ViewPager) findViewById(R.id.viewpager);

// Create an adapter that knows which fragment is on each page
of SimpleFragmentPagerAdapter = new SimpleFragmentPagerAdapter(this,getSupportFragmentManager()) ;

// Set the adapter to ViewPager
viewPager.setAdapter(adapter) ;

// Layout of the Search tab showing the tabs
TabLayout = findViewById(R.id.tabs) ;

// Link the tab layout to the viewer receiver. It will be
// 1. Update the layout of the tabs when you pass the browser
// 2. Refreshes the pager display when tab
is selected // 3. Set the names of the layout tabs with the titles of the pager view adapters
// by calling the PageTitle()
tabLayout.setupMetViewPager(viewPager);
}
} function.

I used the fragment adapter configuration in another class where I passed the context to the constructor for several tabs

Solution no. 7:

If the title of your tab is from string.xml.
You can stack a clip with a title in the list and then define the title using the TabLayoutMediator. You can easily rearrange, delete or add a new track.

Class MyFragment : Fragmentation() {

cancel the fun onCreateView(..) : See? { “en-US”…}

TabLayoutMediator(tabLayout, viewPager) { tab, position ->
tab.text = pagerAdapter.getTabTitle(position)
}.attach()
}.

closed internal class PagerAdapter(fa: FragmentActivity) : FragmentStateAdapter(fa) {
val pages = listOf(
Pair(HomeFragment.newInstance(), R.string.home),
Pair(GraphFragment.newInstance(), R.string.graph),
Pair(SettingFragment.newInstance(), R.string.setting),
)

Skip the fun createFragment(position: Int): Excerpt [
indicates pages [positions].first
}

Cancel the getItemCount() function: In {
return pages.count()
}

funny getTabTitle (position: Int) : String [
returns getString(pages[position].second)
}
}
}

Good luck!

Related Tags:

 android tabsviewpager2 tablayout java exampleviewpager2 kotlinandroid tab layout with fragmentsviewpager2 with tablayout android kotlin exampleviewpager2 does not support direct child viewsviewpager android example androidhivetab viewpager2 androidviewpager2 tablayout recyclerviewtablayout in androidxtablayout with viewpager2 in fragment androidandroid viewpager2 exampletablayout androidtablayoutmediator not foundtablayoutmediator attached before viewpager2 has an adapterviewpager2 adapter

Leave a comment

Your email address will not be published. Required fields are marked *