TabLayout onTabSelected未调用

时间:2016-07-12 16:24:53

标签: android android-viewpager android-tablayout

我在活动中使用android.support.design.widget.TabLayoutandroid.support.v4.view.ViewPager 没有错误。所有标签都显示罚款,可以选择,滑动工作。

活动代码:

ViewPager mViewPager;
TabLayout mSlidingTabs;
mSlidingTabs = (TabLayout) findViewById(R.id.tabs);
        mSlidingTabs.setupWithViewPager(mViewPager);

        mViewPager.addOnPageChangeListener(new ViewPager.OnPageChangeListener() {
            @Override
            public void onPageScrolled(int position, float positionOffset, int positionOffsetPixels) {
                Log.w(TAG, "onPageScrolled");// nothing happens here either
            }

            @Override
            public void onPageSelected(int position) {
                Log.w(TAG, "onPageSelected");// nothing happens here either
            }

            @Override
            public void onPageScrollStateChanged(int state) {
                Log.w(TAG, "onPageScrollStateChanged");// nothing happens here either
            }
        });
        mSlidingTabs.setOnTabSelectedListener(
                new TabLayout.ViewPagerOnTabSelectedListener(mViewPager) {
                    @Override
                    public void onTabSelected(TabLayout.Tab tab) {
                        super.onTabSelected(tab);
                        Log.w(TAG, "selected");
                    }
                    @Override
                    public void onTabUnselected(TabLayout.Tab tab) {
                        Log.w(TAG, "onTabUnselected");
                    }

                    @Override
                    public void onTabReselected(TabLayout.Tab tab) {
                        Log.w(TAG, "onTabReselected");
                    }
                });  

我错过了什么?

2 个答案:

答案 0 :(得分:0)

下面的代码tablayout& viewpager snyc

  pagerList.addOnPageChangeListener(new TabLayout.TabLayoutOnPageChangeListener(tabLayout));

答案 1 :(得分:0)

尝试按此顺序执行操作:

  1. 调用`setupWithViewPager();
  2. 添加onTabSelectedListener();
  3. 喜欢这样:

    mSlidingTabs.setupWithViewPager(mViewPager);
    mSlidingTabs.setOnTabSelectedListener(
      new TabLayout.ViewPagerOnTabSelectedListener(mViewPager) {
        @Override
        public void onTabSelected(TabLayout.Tab tab) {
            super.onTabSelected(tab);
            Log.d(TAG, "Tab selected");
        }
    });
    

    如果这不起作用,则问题必须超出您提供的代码范围。如果是这种情况,请提供一些反馈,以便我们进一步调查。