The author | ithuangqing

Statement | this is the original ithuangqing, release has been authorized, without author permission please do not reprint

preface

When learning TabLayout in order to deepen their memory, TabLayout and ViewPager for some simple packaging, can be more quickly generated we want to slide the page, for beginners to practice or good, due to the limited technical level, god do not spray!

The implementation process

First of all, when we use TabLayout, we need to add dependencies in our project, we need to add dependencies in app Gradle:

compile 'com. Android. Support: design: 24.2.0'Copy the code

First we create the main layout, a TabLayout and a ViewPager

<LinearLayout        android:layout_width="match_parent"        android:layout_height="match_parent"        android:orientation="vertical">        <android.support.design.widget.TabLayout            android:layout_width="match_parent"            android:background="@color/colorPrimary"            app:tabGravity="fill"            app:tabIndicatorColor="@color/colorAccent"            app:tabMode="fixed"            app:tabSelectedTextColor="@color/colorAccent"            app:tabTextColor="@android:color/white"            android:id="@+id/mTabLayout"            android:layout_height="wrap_content">        </android.support.design.widget.TabLayout>        <android.support.v4.view.ViewPager            android:id="@+id/mViewPager"            android:layout_width="match_parent"            android:layout_height="match_parent">        </android.support.v4.view.ViewPager>    </LinearLayout>Copy the code

Then we create the corresponding fragment and add the layout to it

public class Fragment1 extends Fragment {    @Nullable    @Override    public View onCreateView(LayoutInflater inflater, @Nullable ViewGroup container, @Nullable Bundle savedInstanceState) {        return inflater.inflate(R.layout.layout1,null);    }}Copy the code

I’ll just create two fragments here for demonstration purposes. Next we implement tabLayout + ViewPager to implement the sliding logic of the sliding option, as shown in the following code.

 protected void onCreate(Bundle savedInstanceState) {        super.onCreate(savedInstanceState);        setContentView(R.layout.activity_main);        mTabLayout = (TabLayout)findViewById(R.id.mTabLayout);        mViewPager = (ViewPager)findViewById(R.id.mViewPager);        mTitle = new ArrayList<>();        mTitle.add("Home page");        mTitle.add("Center");        mFragment = new ArrayList<>();        mFragment.add(new Fragment1());        mFragment.add(new Fragment2());       /** * preload */        mViewPager.setOffscreenPageLimit(mFragment.size());        /** * sets the adapter */        mViewPager.setAdapter(new FragmentPagerAdapter(getSupportFragmentManager()) {            @Override            public Fragment getItem(int position) {                return mFragment.get(position);            }            @Override            public int getCount() {                return mFragment.size();            }            @Override            public CharSequence getPageTitle(int position) {                return mTitle.get(position); }}); mTabLayout.setupWithViewPager(mViewPager); }}Copy the code

If you have studied TabLayout before, you will understand this code. The viewPager setup adapter in the above code is the core code for using TabLayout. In my view, TabLayout+ViewPager is used to set the adapter to fill the fragment, and then associate the TabLayout with the ViewPager. We are going to focus on how to implement TabLayout and ViewPager encapsulation, so that you can easily create a sliding Tab in three lines of code after creating a basic layout and Fragment.

Firstly, part of the code is encapsulated in three steps. The first step is to encapsulate the following main code, which is also the core code using Tablayout.

/** * sets the adapter */        mViewPager.setAdapter(new FragmentPagerAdapter(getSupportFragmentManager()) {            @Override            public Fragment getItem(int position) {                return mFragment.get(position);            }            @Override            public int getCount() {                return mFragment.size();            }            @Override            public CharSequence getPageTitle(int position) {                return mTitle.get(position); }}); mTabLayout.setupWithViewPager(mViewPager); }Copy the code

This part of the code is the core, mainly to set up the adapter for ViewPager and implement the association with TabLayout, we first create a utility class ItHqAddTab.

public class ItHqAddTab {    public  static   void addTab(TabLayout tabLayout, ViewPager viewPager, final List<Fragment> fragment, final List<String> title, FragmentManager fragmentManager){        /** * preload */        viewPager.setOffscreenPageLimit(fragment.size());        viewPager.setAdapter(new FragmentPagerAdapter(fragmentManager) {            @Override            public Fragment getItem(int position) {                return fragment.get(position);            }            @Override            public int getCount(a) {                return fragment.size();            }            @Override            public CharSequence getPageTitle(int position) {                returntitle.get(position); }});// TabLayout is associated with ViewPager        tabLayout.setupWithViewPager(viewPager);    }}Copy the code

The wrapper logic is shown above. We create a public addTab and pass in five arguments, especially the last one. To encapsulate the code above, we can simply use one line of code instead of complex logic.

ItHqAddTab.addTab(mTabLayout.mViewPager.mFragment.mTitle.getSupportFragmentManager());Copy the code

Of course, we encapsulate the code for better use in the future, like the following code we also feel cumbersome, so we will carry out simple encapsulation of the following code.

 mTitle = new ArrayList<>();        mTitle.add("Home page");        mTitle.add("Center");        mFragment = new ArrayList<>();        mFragment.add(new Fragment1());        mFragment.add(new Fragment2());Copy the code

Let’s create another ItHqAddTitle utility class like this.

public class ItHqAddTitle {    public static List<String> addTitle(String ... a){        String[] title = a;        List<String> list = Arrays.asList(title);        return list;    }}Copy the code

One of the main problems with wrapping this class is that when you’re creating TAB page names you’re using strings, but what we need here is a List, so we need to convert the string that we got into a List, and another thing because we’re not sure how many titles you want to create, So the argument we pass in is defined as (String… A), so that you can pass as many parameters as you like.

Similarly, the package for adding fragments is almost the same, and the code is posted here.

public class ItHqAddFragment {    public static List<Fragment> addFragment(Fragment ... fragments){       Fragment[] m = fragments;        List<Fragment> fragmentList = Arrays.asList(m);        return fragmentList;    }}Copy the code

As a result, we have encapsulated the main methods into a single utility class.

This makes it easy to swipe a TAB with three lines of code.

mTile = ItHqAddTile.addTile("Home page"."Center");        mFragment = ItHqAddFragment.addFragment(new Fragment(),new Fragment2());        ItHqAddTab.addTab(mTabLayout,mViewPager,mFragment,mTile,getSupportFragmentManager())Copy the code

Make your own open source libraries

With this done, we can easily implement the TAB slide option, which is a good thing to share with others, so we can make the project open source library out!

First we create a new Module based on the project, and then select Library.

Then open the Library you just created and copy all three classes you encapsulated into it.

We also need to add a TabLayout dependency to build.gradle in the new Library, otherwise we will get an error.

After completing the above steps, let’s start the open source journey. We use jitPack to open source the project to Github. The first step is to upload the whole project to Github.

And then add a release.

And then copy the address of our warehouse, such as https://github.com/ithuangqing/ItHqSimpleTabLyout, then I open jitpack, copying the warehouse link, click the look up, click on the git it.

We then get the following dependency code.

The maven {url ‘https://www.jitpack.io’} and the compile ‘com. Making. Ithuangqing: ItHqSimpleTabLyout: v1.3’

Depending on our project, you can use this library

So let’s see how it works. So let’s start with a new project, The maven {url ‘https://www.jitpack.io’} and the compile ‘com. Making. Ithuangqing: ItHqSimpleTabLyout: v1.3’ dependence to our project

Click Sync to create a simple layout and fragment, and you can use three lines of code to create a TAB slide option with TabLayout and ViewPager.

conclusion

The above is some simple encapsulation of TabLayot and ViewPager and how to create your own open source library. The technical point itself is not difficult, but involves the encapsulation and creation of open source library, for beginners can get some dry goods.

GitHub address of the project

https://github.com/ithuangqing/ItHqSimpleTabLyout

As I am currently in school, I have just started to learn Android and my technical level is limited. I am very glad if this article can help you. If there is anything wrong in what I said, please kindly give me your advice, thank you!

The related

Android realizes 3D flip of dialog

Are you bothered by pull-down refresh and pull-up loading?