【问题标题】:How can I switch between tabs in a TabLayout programatically from within a fragment如何从片段内以编程方式在 TabLayout 中的选项卡之间切换
【发布时间】:2020-06-01 05:50:50
【问题描述】:

如何从当前显示在选定选项卡中的片段内以编程方式在 TabLayout 中的选项卡之间切换? 我的片段中有一个按钮,我想切换到另一个选项卡\片段,但我不能使用 - tabs.getTabAt(2).select();,因为它在片段内部不起作用。

【问题讨论】:

    标签: android android-fragments android-tablayout


    【解决方案1】:

    Activity 中创建方法

    public void changeTab(int position){
        tabs.getTabAt(position).select();
    }
    

    并在您的Fragment中使用

    ((YourActivity) getActivity()).changeTab(2);
    

    【讨论】:

    • 当我尝试获取 TabLayout“标签”的引用时,它似乎显示错误 - “尝试调用虚拟方法 'void com.google.android.material.tabs.TabLayout$Tab .select()' on a null object reference”,为了清楚起见,我确实使用了 findViewByID 和所有内容,但它仍然认为它为 null。
    • findViewById 必须在上述changeTab 方法调用之前调用。还要确保它成功找到TabLayout,您的错误表明findViewById 找不到TabLayout
    • findViewById 在 changeTab 之前调用。当在片段中单击按钮时调用bacuase changeTab,并在父活动的onCreate中调用findViewById ...似乎它无法找到TabLayout但我就是不知道为什么......
    • 你的错误是...select()' on a null object reference",所以TabLayout不为空,Tab本身在position为空...
    【解决方案2】:

    我现在确实解决了它,而且很容易。 要从片段中切换选项卡,需要访问 tabLayout 并使用 tabs = getActivity().findViewById(R.id.tabLayout); 工作得很好,然后像上一个答案中建议的 snachmsm 一样调用 tabs.getTabAt(1).select();

    【讨论】:

    • 很高兴我得到了帮助 :)
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2014-10-09
    • 1970-01-01
    • 2019-07-23
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多