Tab Layout and ViewPager

Posted by hhisc383 on Thu, 27 Jun 2019 21:53:19 +0200

I. Introduction

Above is the homepage Tab of the Android side of the brief book. Tab is also very common in other apps. It can be implemented in many ways: TabHost, custom controls (third-party libraries), RadioGroup and so on. This article mainly introduces the use of TabLayout in the Android Design library.

TabLayout and ViewPager are the most common ways to use them, as shown in the figure above. Next, let's break through them one by one.

2. Introduction to T abLayout's attributes

I'm not so nonsense here to tell you how to use T abLayout simply. It's pediatrics. Today I'm talking about some attributes or usages that are often forgotten or common in development.

  1. Simple usage

    First introduce the design library:
    Adding dependencies

This is the class under the Android Design package, which is the UI package introduced by Android 5.0.

compile 'com.android.support:design:25.2.0'

(1) Introducing TabLayou into the layout

             <android.support.design.widget.TabLayout

              android:id="@+id/tabLayout"

              android:layout_width="wrap_content"

              android:layout_height="wrap_content"/>

(2) Simply set up calls in code

    tabLayout= (TabLayout) findViewById(R.id.tabLayout);

    tabLayout.addTab(tabLayout.newTab().setText("Tab 1"));

    tabLayout.addTab(tabLayout.newTab().setText("Tab 2"));

    tabLayout.addTab(tabLayout.newTab().setText("Tab 3"));

Simple usage is that simple. This is not the point I want to share today. Today, I want to share some of T abLayout's error-prone attributes and how to use them in conjunction with V iewPager.

2. Introduction to TabLayout's attributes

  • 1. Change the color of TabLayout
    In development, when you see product prototypes or UI effect maps, is there an impulse to curse, how to change it? Actually, it's better to accumulate more books in the process of development. It's not unreasonable that there are few books in use. Get to the point.
    (1) Change the color of the selected font
     app:tabSelectedTextColor="#ffffff" // Selected Tab text color
     app:tabTextColor="#000000" // Unselected Tab text color
     app:tabTextAppearance="@style/Base.TextAppearance.AppCompat.Large" // Text Style

(2) Change the color and height of the indicator subscript

         app:tabIndicatorHeight="10dp"  //Indicator height. When the height is zero, there is no horizontal line indicating the subscript.
      app:tabIndicatorColor="@color/colorPrimary"   // Indicator color

(3) Change the background color of the entire TabLayout

      app:tabBackground="color"
  • 2 Change the text size of Tab
    Always feel that the font is a little small, so I want to find a way to make the font bigger, as if there is no direct way to get bigger, but I found this:
    app:tabTextAppearance="@android:style/TextAppearance.Holo.Large"//Set up the appearance of the text

As long as you can set style, there's nothing terrible about it, right?

3. Change the height of indicator subscript

    app:tabIndicatorHeight="4dp"

4. Add icons

    tabLayout.addTab(tabLayout.newTab().setText("Tab 1").setIcon(R.mipmap.ic_launcher));

5.Tab model
What should we do when there is a lot of data? The second Tab in the brief book can be sliding.

For example:
    tabLayout.addTab(tabLayout.newTab().setText("Tab 4"));

    tabLayout.addTab(tabLayout.newTab().setText("Tab 5"));

    tabLayout.addTab(tabLayout.newTab().setText("Tab 6"));

    tabLayout.addTab(tabLayout.newTab().setText("Tab 7"));

    tabLayout.addTab(tabLayout.newTab().setText("Tab 8"));

    tabLayout.addTab(tabLayout.newTab().setText("Tab 9"));

    tabLayout.addTab(tabLayout.newTab().setText("Tab 10"));

    tabLayout.addTab(tabLayout.newTab().setText("Tab 11"));

Then set the property to:

app:tabMode="scrollable"

The default is fixed: fixed, labels are often squeezed and cannot slide.

6. Add padding
Set the addition of child controls within Tab:


    app:tabPadding="xxdp"

    app:tabPaddingTop="xxdp"

    app:tabPaddingStart="xxdp"

    app:tabPaddingEnd="xxdp"

    app:tabPaddingBottom="xxdp"

Set the addition of the entire TabLayout:

    app:paddingEnd="xxdp"

    app:paddingStart="xxdp"

7. Display mode of content

app:tabGravity="center"//In the middle, if it's fill ed, it's full.

8. Tab's Width Limitation
Set the maximum tab width:

   app:tabMaxWidth="xxdp"
Set the minimum tab width:
    app:tabMinWidth="xxdp"

9.Tab's "Margin"
The offset of the starting position of TabLayout:

app:tabContentStart="100dp"

10.TabLayout's listening events
OnTabSelectedListener():

    tabLayout.setOnTabSelectedListener(newTabLayout.OnTabSelectedListener() {

    @Override

    public voidonTabSelected(TabLayout.Tab tab) {

    //Selected tab logic

    }

    @Override

    public voidonTabUnselected(TabLayout.Tab tab) {

    //Logic of unchecked tab

    }

    @Override

    public voidonTabReselected(TabLayout.Tab tab) {

    //Select tab's logic again

    }

    });

11. Linkage with ViewPager

tabLayout.setupWithViewPager(Viewpager);

12. Select an item by default

tablayout.getTabAt(position).select();

3. Examples of how to interact with ViewPager

1. Layout file

<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:tianya="http://schemas.android.com/apk/res-auto"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    android:background="@color/common_light_gap_bg"
    android:orientation="vertical" >
    <!-- Top input bar -->

    <!-- <LinearLayout
        android:id="@+id/llinput"
        android:layout_width="fill_parent"
        android:layout_height="wrap_content"
        android:padding="5dip"
        android:background="@color/application_bg"
        android:orientation="horizontal" >

        <EditText
            android:id="@+id/txt_input"
            android:layout_width="fill_parent"
            android:layout_height="wrap_content"
            android:layout_gravity="center_vertical"
            android:gravity="center_vertical"
            android:singleLine="true"
            android:textColor="@android:color/black" />

        <ImageView
            android:id="@+id/icon_clean"
            android:layout_width="wrap_content"
            android:layout_height="wrap_content"
            android:layout_gravity="center"
            android:visibility="invisible" />
    </LinearLayout> -->

    <cn.tianya.light.widget.SearchBoxTushuo
        android:id="@+id/searchbox"
        android:layout_width="fill_parent"
        android:layout_height="wrap_content" />

    <!-- Friends List -->
    <android.support.design.widget.TabLayout
        android:id="@+id/tabs"
        android:layout_width="match_parent"
        android:layout_height="39dp"
        android:background="@color/white"
        tianya:tabIndicatorColor="@color/noteitem_owner"
        tianya:tabSelectedTextColor="@color/noteitem_owner"
        tianya:tabTextAppearance="@style/tab_text_style"
        tianya:tabTextColor="@color/reward_price"/>

    <!--Sliding layout content-->
    <android.support.v4.view.ViewPager
        android:id="@+id/vp_view"
        android:layout_width="match_parent"
        android:layout_height="wrap_content"/>
</LinearLayout>

2. java code settings

public class MultiContactSelectActivity extends Activity {
    private TabLayout mTabLayout;
    private ViewPager mViewPager;
    private LayoutInflater mInflater;
    private List<String> mTitleList = new ArrayList<>();//Page Card Title Collection
    private View view1, view2;//Page Card View
    private List<View> mViewList = new ArrayList<>();//Page Card View Collection
        @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.multi_contact_select_main);
        initViews();
    }
    private void initViews() {
        mViewPager = (ViewPager) findViewById(R.id.vp_view);
        mTabLayout = (TabLayout) findViewById(R.id.tabs);

        mInflater = LayoutInflater.from(this);

        view1 = mInflater.inflate(R.layout.contact_select_page, null);
        view2 = mInflater.inflate(R.layout.contact_select_page, null);
        //Add Page Card View
        mViewList.add(view1);
        mViewList.add(view2);
        //Add Page Card Title
        mTitleList.add(getResources().getString(R.string.my_friends));
        mTitleList.add(getResources().getString(R.string.my_fans));
        mTabLayout.setTabMode(TabLayout.MODE_FIXED);//Set tab mode, currently the default mode for the system
        mTabLayout.addTab(mTabLayout.newTab().setText(mTitleList.get(0)));//Add tab tab tab
        mTabLayout.addTab(mTabLayout.newTab().setText(mTitleList.get(1)));

        MyPagerAdapter mAdapter = new MyPagerAdapter(mViewList);
        mViewPager.setAdapter(mAdapter);//Setting up an adapter for ViewPager
        mTabLayout.setupWithViewPager(mViewPager);//Associate TabLayout with ViewPager.
        mTabLayout.setTabsFromPagerAdapter(mAdapter);//Setting up an adapter for Tabs
        mViewPager.addOnPageChangeListener(new ViewPager.OnPageChangeListener() {
            @Override
            public void onPageScrolled(int position, float positionOffset, int positionOffsetPixels)  {

            }

            @Override
            public void onPageSelected(int position) {
                //Logic after tab is selected
                }
            }

            @Override
            public void onPageScrollStateChanged(int state) {

            }
        });


    }


    //ViewPager adapter
    class MyPagerAdapter extends PagerAdapter {
        private List<View> mViewList;

        public MyPagerAdapter(List<View> mViewList) {
            this.mViewList = mViewList;
        }

        @Override
        public int getCount() {
            return mViewList.size();//Page Card Number
        }

        @Override
        public boolean isViewFromObject(View view, Object object) {
            return view == object;//Official Recommendation
        }

        @Override
        public Object instantiateItem(ViewGroup container, int position) {
            container.addView(mViewList.get(position));//Add Page Card
            return mViewList.get(position);
        }

        @Override
        public void destroyItem(ViewGroup container, int position, Object object) {
            container.removeView(mViewList.get(position));//Delete page cards
        }

        @Override
        public CharSequence getPageTitle(int position) {
        //This must be written here, otherwise the title of the card will not show.
            return mTitleList.get(position);//Page Card Title
        }
    }

}

Summary: In conjunction with ViewPager, you need to rewrite adapter's getPageTitle, otherwise you cannot display the tag on TabLayout
You can refer to these two articles and write them well.
Detailed T abLayout attributes
The most detailed TabLayout

Topics: Android xml encoding Java