Use TabLayout in AndroidSupportDesign

Source: Internet
Author: User

Use TabLayout in AndroidSupportDesign

In the previous blog "High Force Grid UI-ASD (Android Support Design)", we roughlyTabLayoutI have a preliminary understanding of this blog.TabLayoutTo continue with the explanation:Android Support DesignLibrary, except:FAB,SnackBarAnd so on.TabLayouT is OK.CollapsingToolbarLayoutSuch controls are too encapsulated and can only be used in those scenarios (purely personal opinions ).
ThatTabLayoutWhat about it? The previous blog is just a simple introduction. Today we use TabLayout with ViewPager to use the following.
Before getting started, let's take a look at the instructions in the official documentation on how to interact with ViewPager:

You shoshould set a listener via setOnTabSelectedListener (OnTabSelectedListener) to be notified when any tab's selection state has been changed.
If you're using a ViewPager together with this layout, you can use setTabsFromPagerAdapter (PagerAdapter) which will populate the tabs using the given PagerAdapter's page titles. you shoshould also use a TabLayout. tabLayoutOnPageChangeListener to forward the scroll and selection changes to this layout

Well, it looks very easy. A simple translation is:

SetOnTabSelectedListener is used to set a listener to respond to the selection status of the tab.
You can use setTabsFromPagerAdapter to use the page title of PagerAdapter.
Use TabLayout. TabLayoutOnPageChangeListener to move together

OK. In general, the steps have been listed in the general translation process. Next we just need to follow the steps above to write our code.
Come on ~, First, the xml layout file is displayed:

<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"    xmlns:app="http://schemas.android.com/apk/res-auto"    xmlns:tools="http://schemas.android.com/tools"    android:layout_width="match_parent"    android:layout_height="match_parent"    android:orientation="vertical"    tools:context=".MainActivity">    <android.support.design.widget.TabLayout        android:id="@+id/tl"        android:layout_width="match_parent"        android:layout_height="wrap_content"        app:tabIndicatorColor="#FF00FF00"        app:tabSelectedTextColor="#FF00FF00"        app:tabTextColor="#FF000000"        app:tabMode="scrollable"        app:tabGravity="center"/>    <android.support.v4.view.ViewPager        android:id="@+id/viewpager"        android:layout_width="match_parent"        android:layout_height="wrap_content"/></LinearLayout>

Well, it's very simple.TabLayoutAnd oneViewPagerAnd is arranged up and down.

In Activity, we first need to find the two controls:

    mTabLayout = (TabLayout) findViewById(R.id.tl);    mViewPager = (ViewPager) findViewById(R.id.viewpager);

To demonstrate the program, two pseudo data files are required to act as the content and title of ViewPager.

private String[] mTitle = new String[20];private String[] mData = new String[20];{    for(int i=0;i<20;i++) {        mTitle[i] = "title" + i;        mData[i] = "data" + i;    }}

Next, we will follow the steps above to compile the Code a little bit:
Step 1: SetTabLayoutTab listening:

mTabLayout.setOnTabSelectedListener(new TabLayout.OnTabSelectedListener() {            @Override            public void onTabSelected(TabLayout.Tab tab) {                mViewPager.setCurrentItem(tab.getPosition());            }            @Override            public void onTabUnselected(TabLayout.Tab tab) {            }            @Override            public void onTabReselected(TabLayout.Tab tab) {            }        });

When we select the tab, letviewpagerSelect the corresponding item.
Step 2: SetTabThe title is fromPagerAdapter.getPageTitle().

mTabLayout.setTabsFromPagerAdapter(mAdapter);

Step 3: SetTabLayout.TabLayoutOnPageChangeListenerWho should I set it? Of course it's ViewPager. How can I set it?

final TabLayout.TabLayoutOnPageChangeListener listener =                new TabLayout.TabLayoutOnPageChangeListener(mTabLayout);mViewPager.addOnPageChangeListener(listener);

Oh, it turns outTabLaout.TabLayoutOnPageChangeLisetenerInherited fromOnPageChangeListenerNo, let's see:

public static class TabLayoutOnPageChangeListener implements OnPageChangeListener {...}

Note: Here is addOnPageChangeListener, that is, you can add N Listener instead of overwriting.
Here, we have finished all the steps, but don't forget to set the Adapter for ViewPage.

mViewPager.setAdapter(mAdapter);

Finally, the Adapter code:

private PagerAdapter mAdapter = new PagerAdapter() {        @Override        public CharSequence getPageTitle(int position) {            return mTitle[position];        }        @Override        public int getCount() {            return mData.length;        }        @Override        public Object instantiateItem(View container, int position) {            TextView tv = new TextView(MainActivity.this);            tv.setTextSize(30.f);            tv.setText(mData[position]);            ((ViewPager) container).addView(tv);            return tv;        }        @Override        public void destroyItem(ViewGroup container, int position, Object object) {            ((ViewPager) container).removeView((View) object);        }        @Override        public boolean isViewFromObject(View view, Object object) {            return view == object;        }    };

Run the code to see the effect:

Is it easy? A few lines of code to achieve this effect, of course, you can also choose to rewrite the View method, for more information, see create an Indicator, the most easy-to-use Tab Indicator in history.
...
If you feel this is simple, you are too satisfied. Google also provides us with a method to encapsulate these steps so that our developers can do it in one step.public void setupWithViewPager (ViewPager viewPager), Continue to see the instructions in the document:

The one-stop shop for setting up this TabLayout with a ViewPager.

This method will:

Add a ViewPager. OnPageChangeListener that will forward events to this TabLayout.
Populate the TabLayout's tabs from the ViewPager's PagerAdapter.
Set our TabLayout. OnTabSelectedListener which will forward selected events to the ViewPager

The general explanation is:

This method isaddOnPageChangeListenerAndsetOnTabSelectedListener.

So we comment out the corresponding code and replace itsetupWithViewPager.

//        mTabLayout.setOnTabSelectedListener(new TabLayout.OnTabSelectedListener() {//            @Override//            public void onTabSelected(TabLayout.Tab tab) {//                mViewPager.setCurrentItem(tab.getPosition());//            }////            @Override//            public void onTabUnselected(TabLayout.Tab tab) {////            }////            @Override//            public void onTabReselected(TabLayout.Tab tab) {////            }//        });        mTabLayout.setTabsFromPagerAdapter(mAdapter);//        final TabLayout.TabLayoutOnPageChangeListener listener =//                new TabLayout.TabLayoutOnPageChangeListener(mTabLayout);//        mViewPager.addOnPageChangeListener(listener);        mViewPager.setAdapter(mAdapter);        mTabLayout.setupWithViewPager(mViewPager);

The effect is still the above effect, but the amount of code is obviously less, only two lines of code are required.
But pay attention to the following,setupWithViePagerMust be inViewPager.setAdapter()Call later! Why? Find the answer from the source code:

public void setupWithViewPager(ViewPager viewPager) {    PagerAdapter adapter = viewPager.getAdapter();    if(adapter == null) {        throw new IllegalArgumentException("ViewPager does not have a PagerAdapter set");    } else {        ...    }}

First obtain the Adapter on the ViewPager. If there is no Adapter, an exception is thrown!
NowTabLayoutAndViewPagerI have explained the usage of one piece. I believe it is very simple, and only two lines of code can be done.
They will often be used in future projects, but they are so easy and not afraid ~~

Copyright Disclaimer: This article is an original article by the blogger and cannot be reproduced without the permission of the blogger.

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.