天天看点

TabLayout 遇到那些坑

  • 如何使用 :注意事项
<?xml version="1.0" encoding="utf-8"?>
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    xmlns:app="http://schemas.android.com/apk/res-auto">
    <android.support.design.widget.TabLayout
        android:id="@+id/tabs"
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        app:tabIndicatorColor="@color/colorAccent"
        app:tabSelectedTextColor="@color/colorAccent"
<android.support.design.widget.TabItem
    android:layout_width="wrap_content"
    android:layout_height="wrap_content"
    android:text="android"
<android.support.design.widget.TabItem
    android:layout_width="wrap_content"
    android:layout_height="wrap_content"
    android:text="java"
<android.support.design.widget.TabItem
    android:layout_width="wrap_content"
    android:layout_height="wrap_content"
    android:text="javascript"
<android.support.design.widget.TabItem
    android:layout_width="wrap_content"
    android:layout_height="wrap_content"
    android:icon="@drawable/ic_launcher"
    </android.support.design.widget.TabLayout>
</RelativeLayout>      

效果图:

一些坑 和 ViewPager 一起使用需要注意

  • 我在和ViewPager一起使用时,遇到了一些坑,

按照官方给出的示例,我写出来的代码是这样的

布局代码

<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    android:orientation="vertical"
    xmlns:app="http://schemas.android.com/apk/res-auto">
    <android.support.design.widget.TabLayout
        android:id="@+id/tabs"
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        app:tabIndicatorColor="@color/colorAccent"
        app:tabSelectedTextColor="@color/colorAccent"
    <android.support.v4.view.ViewPager
        android:id="@+id/vp_pager"
        android:layout_width="match_parent"
        android:layout_height="0dp"
        android:layout_weight="1"
</LinearLayout>      

java代码

public class MainActivity extends AppCompatActivity

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);

        ViewPager viewPager = (ViewPager) findViewById(R.id.vp_pager);
        MyAdapter myAdapter = new MyAdapter();
        viewPager.setAdapter(myAdapter);

        TabLayout tabLayout = (TabLayout) findViewById(R.id.tabs);
        tabLayout.addTab(tabLayout.newTab().setText("Tab 1"));
        tabLayout.addTab(tabLayout.newTab().setText("Tab 2"));
        tabLayout.addTab(tabLayout.newTab().setText("Tab 3"));
        tabLayout.addTab(tabLayout.newTab().setText("Tab 4"));
        tabLayout.setupWithViewPager(viewPager);




    }

    class MyAdapter extends PagerAdapter {

        @Override
        public int getCount() {
            return 4;
        }

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

        @Override
        public Object instantiateItem(ViewGroup container, int position) {
            ImageView imageView = new ImageView(MainActivity.this);
            imageView.setBackgroundResource(R.drawable.ic_launcher);
            container.addView(imageView);
            return imageView;
        }

        @Override
        public void destroyItem(ViewGroup container, int      

然而,看到运行结果的我一脸懵逼.

TabLayout 遇到那些坑

踏马达我的字去哪了,我首先想到的就是,是不是ViewPager布局太高了,把Tab盖住了,然而减少了的ViewPager的高度还是不行,

是不是颜色不对。。。

是不是字号不对…

然后,我又尝试着注释掉了这行代码

tabLayout.setupWithViewPager(viewPager);      
TabLayout 遇到那些坑

虽然Tab和 ViewPagre 失去了关联,但是最起码按我的想法展示出来了.

现在已经找到了罪魁祸首,就是 ​

​tabLayout.setupWithViewPager(viewPager);​

​ 搞的鬼,然后我点进去查看一下源码,

/**
     * The one-stop shop for setting up this {@link TabLayout} with a {@link ViewPager}.
     *
     * <p>This method will link the given ViewPager and this TabLayout together so that any
     * changes in one are automatically reflected in the other. This includes adapter changes,
     * scroll state changes, and clicks. The tabs displayed in this layout will be populated
     * from the ViewPager adapter's page titles.</p>
     *
     * <p>After this method is called, you will not need this method again unless you want
     * to change the linked ViewPager.</p>
     *
     * <p>If the given ViewPager is non-null, it needs to already have a
     * {@link PagerAdapter} set.</p>
     *
     * @param
    public void setupWithViewPager(@Nullable final ViewPager viewPager) {
        if (mViewPager != null && mPageChangeListener != null) {
            // If we've already been setup with a ViewPager, remove us from it
            mViewPager.removeOnPageChangeListener(mPageChangeListener);
        }

        if (viewPager != null) {
            final PagerAdapter adapter = viewPager.getAdapter();
            if (adapter == null) {
                throw new IllegalArgumentException("ViewPager does not have a PagerAdapter set");
            }

            mViewPager = viewPager;

            // Add our custom OnPageChangeListener to the ViewPager
            if (mPageChangeListener == null) {
                mPageChangeListener = new TabLayoutOnPageChangeListener(this);
            }
            mPageChangeListener.reset();
            viewPager.addOnPageChangeListener(mPageChangeListener);

            // Now we'll add a tab selected listener to set ViewPager's current item
            setOnTabSelectedListener(new ViewPagerOnTabSelectedListener(viewPager));

            // Now we'll populate ourselves from the pager adapter
            setPagerAdapter(adapter, true);
        } else {
            // We've been given a null ViewPager so we need to clear out the internal state,
            // listeners and observers
            mViewPager = null;
            setOnTabSelectedListener(null);
            setPagerAdapter(null, true);
        }
    }      

貌似没神魔问题,再看看 setPagerAdapter

private void setPagerAdapter(@Nullable final PagerAdapter adapter, final boolean addObserver) {
        if (mPagerAdapter != null && mPagerAdapterObserver != null) {
            // If we already have a PagerAdapter, unregister our observer
            mPagerAdapter.unregisterDataSetObserver(mPagerAdapterObserver);
        }

        mPagerAdapter = adapter;

        if (addObserver && adapter != null) {
            // Register our observer on the new adapter
            if (mPagerAdapterObserver == null) {
                mPagerAdapterObserver = new PagerAdapterObserver();
            }
            adapter.registerDataSetObserver(mPagerAdapterObserver);
        }

        // Finally make sure we reflect the new adapter      

貌似也没什么问题啊,此时我万念俱灰,又抱着一丝希望点开看看 populateFromPagerAdapter();

private void populateFromPagerAdapter() {
        removeAllTabs();

        if (mPagerAdapter != null) {
            final int adapterCount = mPagerAdapter.getCount();
            for (int i = 0; i < adapterCount; i++) {
                addTab(newTab().setText(mPagerAdapter.getPageTitle(i)), false);
            }

            // Make sure we reflect the currently set ViewPager item
            if (mViewPager != null && adapterCount > 0) {
                final int curItem = mViewPager.getCurrentItem();
                if (curItem != getSelectedTabPosition() && curItem < getTabCount()) {
                    selectTab(getTabAt(curItem));
                }
            }
        } else      

握草,

removeAllTabs();      

就只这行代码,竟然在这儿 remove 掉了我之前设置的所有 Tab ,我真是想日了个狗啊,这在官方文档上没一点提示啊.

然后我又修改了一下代码

public class MainActivity extends AppCompatActivity

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);

        ViewPager viewPager = (ViewPager) findViewById(R.id.vp_pager);
        MyAdapter myAdapter = new MyAdapter();
        viewPager.setAdapter(myAdapter);


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

        tabLayout.addTab(tabLayout.newTab().setText("Tab 1"));
        tabLayout.addTab(tabLayout.newTab().setText("Tab 2"));
        tabLayout.addTab(tabLayout.newTab().setText("Tab 3"));
        tabLayout.addTab(tabLayout.newTab().setText("Tab 4"));


        tabLayout.setupWithViewPager(viewPager);

        tabLayout.getTabAt(0).setText("Tab1");
        tabLayout.getTabAt(1).setText("Tab2");
        tabLayout.getTabAt(2).setText("Tab3");
        tabLayout.getTabAt(3).setText("Tab4");

    }

    class MyAdapter extends PagerAdapter {

        @Override
        public int getCount() {
            return 4;
        }

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

        @Override
        public Object instantiateItem(ViewGroup container, int position) {
            ImageView imageView = new ImageView(MainActivity.this);
            imageView.setBackgroundResource(R.drawable.ic_launcher);
            container.addView(imageView);
            return imageView;
        }
        @Override
        public void destroyItem(ViewGroup container, int      
TabLayout 遇到那些坑

真感动人!!!!!!!!终于得到我想要的结果了,