Tablayout viewpage usage example fragmenttabhost usage example

The previous article introduced the use of fragmenttabhost to use tab navigation; By Android 5.0, tablayout was launched. Therefore, it is necessary to understand tablayout.

First, let's look at mainactivity. It looks a little more because it contains the code of toolbar:

First, initialize tablayout and viewpager, then create an instance of myviewpageradapter and add fragments to it.

Let's take a look at the mysterious myviewpageradapter.

Here, we have rewritten several methods, namely getitem, getcount and getpagetitle. So can our quantity be passed in?

Don't be afraid. When we call setadapt, we actually pass the adapt into viewpager. When we need to get the quantity, we can call this method directly.

Tablayout.setupwithviewpager (viewpager) connects tabs with viewpages so that they change when they change. In tablaout, you can use viewpager.getadapt to get the adapts we just put in; In this way, both have the variable adapt.

Looking at the source code, you can find that tablayout and viewpager set or add listeners to each other, so that you can switch views whether you slide the viewpager or click the tab, and the two can be synchronized.

We can take a specific look at viewpagerontabselectedlistener and find that it implements the interface of tablayout.ontbselectedlistener. In the constructor, assign the viewpager variable to the internal variable, so that when the tab is selected, we can obtain the position of the selected tab, and then set the setting to display the fragment at the same position.

When sliding the page, return onpageselected and pass in the currently selected pager. At this time, just specify the corresponding tab. In this way, the two are well synchronized.

Let's look at the layout file again:

Because of the toolbar, the layout file looks a little complex, but it's actually very simple.

Simplified layout (ID may not be right, but copied from other places):

As for the fragment file, you can refer to the layout in the previous article

Fragmenttabhost usage example

Or directly view the location of the source code:

https://github.com/huanshen/Learn-Android/tree/master/TablayoutViewpager

The content of this article comes from the network collection of netizens. It is used as a learning reference. The copyright belongs to the original author.
THE END
分享
二维码
< <上一篇
下一篇>>