【问题标题】:how to set tablayout position without triggering onTabSelectedListener?如何在不触发 onTabSelectedListener 的情况下设置 tablayout 位置?
【发布时间】:2019-06-28 13:47:36
【问题描述】:

我有这样的tablayout。当这个片段出现时,我想根据onCreateView中的某些条件以编程方式设置选项卡布局位置(即下划线)

我正在使用下面的代码,以编程方式将下划线移动到“两个”选项卡

    lateinit var tabLayout : TabLayout

    override fun onCreateView(): View? {

        tabLayout.getTabAt(1)?.select()
        return View
    }

但不幸的是,tabLayout.getTabAt(1)?.select() 代码会自动触发我的onTabSelectedListener,如下面的代码

 tabLayout.addOnTabSelectedListener(object: TabLayout.OnTabSelectedListener {

            override fun onTabSelected(tab: TabLayout.Tab?) {

             // this part will automatically called

            }

            override fun onTabReselected(tab: TabLayout.Tab?) {

            }

            override fun onTabUnselected(tab: TabLayout.Tab?) {

            }


        })

那么如何在不触发 onTabSelectedListener 的情况下设置 tablayout 位置呢?

Java 没问题

【问题讨论】:

  • 你在select()之前还是之后设置了tab监听?
  • 在 select() 之前。

标签: android kotlin android-tablayout


【解决方案1】:

试试这个解决方案。它会帮助你。

当你手动选择时设置addOnTabSelectedListener null 所以,回调不会来。选择后设置addOnTabSelectedListener。所以它会正常工作。

TabLayout.OnTabSelectedListener onTabSelectedListener = new TabLayout.OnTabSelectedListener() {
                @Override
                public void onTabSelected(TabLayout.Tab tab) {

                }

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

                }

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

                }
            };


tabLayout.addOnTabSelectedListener(null);
tabLayout.getTabAt(1).select();
tabLayout.addOnTabSelectedListener(onTabSelectedListener);

【讨论】:

  • 我们可以删除tabLayout.addOnTabSelectedListener(null);吗?
  • 如果你删除这条线,那么第一次工作完美,但第二次回调会来。
【解决方案2】:

试试这个 -

 private void highLightCurrentTab(int position) {
 for (int i = 0; i < tabLayout.getTabCount(); i++) {
 TabLayout.Tab tab = tabLayout.getTabAt(i);
 assert tab != null;
 tab.setCustomView(null);
 tab.setCustomView(adapter.getTabView(i));
}

在这里传递位置。

或者试试这个 -

new Handler().postDelayed(() -> {

 myViewPager.setCurrentItem(position, true);

  myTabLayout.setScrollPosition(position, 0f, true);
  },   100);

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2016-11-21
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2013-05-11
    • 2021-05-11
    • 1970-01-01
    相关资源
    最近更新 更多