在Tablayout中的tabLayout.addOnTabSelectedListener(新的TabLayout.OnTabSelectedListener()方法不起作用

时间:2018-07-31 10:29:42

标签: android android-tablayout

我在活动中有三个带有片段的Tab,但是方法addOnTabSelectedListener无法正常工作,我的片段正常工作,并且在调试时我也有viewPager不在方法内部

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

    Intent intent = getIntent();
    pos = intent.getIntExtra("position",0);
    tabLayout.addOnTabSelectedListener(new TabLayout.OnTabSelectedListener() {
        @Override
        public void onTabSelected(TabLayout.Tab tab) {
            viewPager.setCurrentItem(tab.getPosition());

            if (tab.getPosition() == 1) {
              tabLayout.getTabAt(pos).select();
                tabLayout.setBackgroundColor(ContextCompat.getColor(Shop.this,
                        R.color.white));
                if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.LOLLIPOP) {
                    getWindow().setStatusBarColor(ContextCompat.getColor(Shop.this,
                            R.color.white));
                }
            } else if (tab.getPosition() == 2) {
               /* toolbar.setBackgroundColor(ContextCompat.getColor(Shop.this,
                        android.R.color.white));*/
                tabLayout.setBackgroundColor(ContextCompat.getColor(Shop.this,
                        android.R.color.white));
                if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.LOLLIPOP) {
                    getWindow().setStatusBarColor(ContextCompat.getColor(Shop.this,
                            android.R.color.white));
                }
            } else {
               /* toolbar.setBackgroundColor(ContextCompat.getColor(Shop.this,
                        R.color.white));*/
                tabLayout.setBackgroundColor(ContextCompat.getColor(Shop.this,
                        R.color.white));
                if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.LOLLIPOP) {
                    getWindow().setStatusBarColor(ContextCompat.getColor(Shop.this,
                            R.color.white));
                }
            }
        }
        @Override
        public void onTabUnselected(TabLayout.Tab tab) {
        }
        @Override
        public void onTabReselected(TabLayout.Tab tab) {
        }
    });

1 个答案:

答案 0 :(得分:0)

您可以尝试这种方式吗

tabLayout.setupWithViewPager(viewPager);
tabLayout.setOnTabSelectedListener(
 new TabLayout.ViewPagerOnTabSelectedListener(viewPager) {
  @Override
  public void onTabSelected(TabLayout.Tab tab) {
      //for selected tab, write your code here...
  }
});

有关详细而清晰的说明,请访问此链接onTabSelected Selected Not Called