TabLayout 标题不显示 原因:

Material Design,是由Google推出的全新的设计语言,谷歌表示,这种设计语言旨在为手机、平板电脑、台式机和“其他平台”提供更一致、更广泛的“外观和感觉”。

1,TabLayout 使我们常用的 design 控件。一般在使用design的设计效果时,我们会配合着 viewPager使用。

这是我碰到的一个小问题记录一下:

tablayout 和viewPager绑定 标题不显示的 问题:

方便有相同的问题的朋友参考探讨:

这是bug效果图:

TabLayout 标题不显示 原因:_第1张图片

纠错:

1,查找原因:

代码:

package com.hero.zhaoq.viewpagerdemo;

import android.support.design.widget.TabLayout;
import android.support.v4.app.Fragment;
import android.support.v4.app.FragmentManager;
import android.support.v4.app.FragmentPagerAdapter;
import android.support.v4.view.ViewPager;
import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;

import com.hero.zhaoq.viewpagerdemo.fragments.Title1Fragment;
import com.hero.zhaoq.viewpagerdemo.fragments.Title2Fragment;
import com.hero.zhaoq.viewpagerdemo.fragments.Title3Fragment;
import com.hero.zhaoq.viewpagerdemo.fragments.Title4Fragment;

import java.util.ArrayList;
import java.util.List;

public class MainActivity extends AppCompatActivity {

    private TabLayout tabLayout;

    private List fragments;

    private  ViewPager viewpager;

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

        tabLayout = (TabLayout) findViewById(R.id.tablayout);
        viewpager = (ViewPager) findViewById(R.id.viewpager);

        initFragment();
        initTablayout();



        //会  清除  tab:
        tabLayout.setupWithViewPager(viewpager);


    }

    //初始化 fragment
    private void initFragment() {
        Title1Fragment fragment1 = new Title1Fragment();
        Title2Fragment fragment2 = new Title2Fragment();
        Title3Fragment fragment3 = new Title3Fragment();
        Title4Fragment fragment4 = new Title4Fragment();

        fragments = new ArrayList<>();

        fragments.add(fragment1);
        fragments.add(fragment2);
        fragments.add(fragment3);
        fragments.add(fragment4);

        viewpager.setAdapter(new FragmentPAdapter(this,
                getSupportFragmentManager(),fragments));
    }

    /**
     * 初始化   tablayout
     */
    private void initTablayout() {
        tabLayout.addTab(tabLayout.newTab());
        tabLayout.addTab(tabLayout.newTab());
        tabLayout.addTab(tabLayout.newTab());
        tabLayout.addTab(tabLayout.newTab());

        //手动  添加标题  必须在 setupwidthViewPager  之后  否则不行
        tabLayout.getTabAt(0).setText("title1");
        tabLayout.getTabAt(1).setText("title2");
        tabLayout.getTabAt(2).setText("title3");
        tabLayout.getTabAt(3).setText("title4");
    }

    //构造器
    private class FragmentPAdapter extends FragmentPagerAdapter {
        //
        public FragmentPAdapter(MainActivity mainActivity, FragmentManager supportFragmentManager, List fragments) {
            super(supportFragmentManager);
        }

        @Override
        public Fragment getItem(int position) {
            return fragments.get(position);
        }

        @Override
        public int getCount() {
            return fragments.size();
        }

        @Override
        public int getItemPosition(Object object) {
            return super.getItemPosition(object);
        }

        @Override
        public long getItemId(int position) {
            return super.getItemId(position);
        }

//        //TODO  注意需要使用   getPageTitle 设置  pager的标题
//        @Override
//        public CharSequence getPageTitle(int position) {
//            return position==0?"title1":position==1?"title2":
//                    position==2?"title3":position==3?"title4":"";
//        }
    }
}

发现当我注释掉联动效果后标题显示:

 //会  清除  tab:
//        tabLayout.setupWithViewPager(viewpager);

打开setupWithViewPager源码 检查:

 private void setupWithViewPager(@Nullable final ViewPager viewPager, boolean autoRefresh,
            boolean implicitSetup) {
        if (mViewPager != null) {
            // If we've already been setup with a ViewPager, remove us from it
            if (mPageChangeListener != null) {
                mViewPager.removeOnPageChangeListener(mPageChangeListener);
            }
            if (mAdapterChangeListener != null) {
                mViewPager.removeOnAdapterChangeListener(mAdapterChangeListener);
            }
        }

        if (mCurrentVpSelectedListener != null) {
            // If we already have a tab selected listener for the ViewPager, remove it
            removeOnTabSelectedListener(mCurrentVpSelectedListener);
            mCurrentVpSelectedListener = null;
        }

        if (viewPager != null) {
            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
            mCurrentVpSelectedListener = new ViewPagerOnTabSelectedListener(viewPager);
            addOnTabSelectedListener(mCurrentVpSelectedListener);

            final PagerAdapter adapter = viewPager.getAdapter();
//注意 此处  adapter 的判断     viewPager 中获取到当前的adapter  进行处理  下面查找到   setPagerAdapter方法:
            if (adapter != null) {
                // Now we'll populate ourselves from the pager adapter, adding an observer if
                // autoRefresh is enabled
                setPagerAdapter(adapter, autoRefresh);
            }

            // Add a listener so that we're notified of any adapter changes

            if (mAdapterChangeListener == null) {
                mAdapterChangeListener = new AdapterChangeListener();
            }
            mAdapterChangeListener.setAutoRefresh(autoRefresh);
            viewPager.addOnAdapterChangeListener(mAdapterChangeListener);

            // Now update the scroll position to match the ViewPager's current item
            setScrollPosition(viewPager.getCurrentItem(), 0f, true);
        } else {
            // We've been given a null ViewPager so we need to clear out the internal state,
            // listeners and observers
            mViewPager = null;
            setPagerAdapter(null, false);
        }

        mSetupViewPagerImplicitly = implicitSetup;
    }

//注意 上面代码中对 adapter 的判断 我们 从viewPager中获取到 当前的adapter: if autoRefresh 可自动刷新 我们添加一个 数据变化的观察者:
// Now we’ll populate ourselves from the pager adapter, adding an observer if
// autoRefresh is enabled

2,查看setPagerAdapter的源码:

   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();
    }

上面代码主要是 添加我们的数据变化的观察者:

如果我们已经有了一个PagerAdapter 则不会添加观察者:
// If we already have a PagerAdapter, unregister our observer

最后执行:populateFromPagerAdapter();方法

查看源码populateFromPagerAdapter:

oid 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));
                }
            }
        }
    }

可以看到 此处 将我们添加的所有 Tab全部移除了。这就是 我们 tabLayout 标题不显示的原因:

3,似乎我们 已经找到了原因 怎么 解决bug 呢?

既然我们在 tabLayout.setupWithViewPager(viewpager) 执行之后 会清除 我们之前添加的的所有的Tab。那我们尝试在 tabLayout.setupWithViewPager(viewpager) 之后再添加 Tab则Tab 是不是就显示了呢?

修改代码:


        //会  清除  tab:
        tabLayout.setupWithViewPager(viewpager);

        //手动  添加标题  必须在 setupwidthViewPager  之后  否则不行
        tabLayout.getTabAt(0).setText("title1");
        tabLayout.getTabAt(1).setText("title2");
        tabLayout.getTabAt(2).setText("title3");
        tabLayout.getTabAt(3).setText("title4");

运行结果:

TabLayout 标题不显示 原因:_第2张图片

搞定bug。

你可能感兴趣的:([Android])