Android-未调用TabLayout侦听器回调

时间:2018-10-01 09:55:28

标签: android android-viewpager android-tablayout

我尝试使用创建类似于Google Play的标签布局。但是我无法捕获点击事件。我的代码如下:

tabLayout.setupWithViewPager(viewPager);
tabLayout.post(new Runnable() {
        @Override
        public void run() {
            tabLayout.addOnTabSelectedListener(new TabLayout.ViewPagerOnTabSelectedListener(viewPager) {
                @Override
                public void onTabSelected(TabLayout.Tab tab) {
                    Log.i("tag", " onTabSelected: " + tab.getPosition());
                }
                .....
            });
        }
    });

onTabSelected从未调用过。

编辑

下面的代码仅适用于刷卡。

tabLayout.addOnTabSelectedListener(new TabLayout.OnTabSelectedListener() {
     ...
}

但我想对点击事件进行项目

2 个答案:

答案 0 :(得分:1)

您不需要Thread

相反,请尝试以下操作:

tabLayout.addOnTabSelectedListener(new TabLayout.OnTabSelectedListener() {
        @Override
        public void onTabSelected(TabLayout.Tab tab) {
           Log.i("tag", " onTabSelected: " + tab.getPosition()); // return the position of the selected Tab

           Toast.makeText(mainActivity.this, "Clicked", Toast.LENGTH_SHORT).show() // this should show the clicked when selecting a tab
        }

        @Override
        public void onTabUnselected(TabLayout.Tab tab) {
        }

        @Override
        public void onTabReselected(TabLayout.Tab tab) {

        }
    });

答案 1 :(得分:0)

  

有时候,我相信问题可能在于ViewPager是   位于TabLayout上方。您要像这样将其放置在下面:

click on tab layout doesn't work at all