Android TabLayout更新选项卡的视图

时间:2016-02-24 06:09:48

标签: java android android-fragments

我有一个TabLayout,我在其中使用tabLayout.addTab(tab, i);动态添加标签。当我在已加载片段的位置添加新选项卡时,片段不会更新。

例如,当我最初添加两个选项卡时会出现这种情况,这些选项卡会被加载,然后在位置1添加另一个选项卡。位置1处的选项卡不会更新。从FragmentPagerAdapter触发更新(我假设调用getItem(int position))需要做什么?

我在调用notifyDataSetChanged()时尝试使用侦听器并在FragmentPagerAdapter上调用tabLayout.addTab(tab, i);,但这并不能解决问题。我也试过在TabLayout上调用invalidate

1 个答案:

答案 0 :(得分:0)

每次要添加标签时都要调用tabLayout.removeAllTabs();。然后只需按所需顺序添加选项卡。

或者你可以写mViewPager.setOffscreenPageLimit(0);,其中mViewPager是你的viewpager。这是此方法的定义 -

/**
     * Set the number of pages that should be retained to either side of the
     * current page in the view hierarchy in an idle state. Pages beyond this
     * limit will be recreated from the adapter when needed.
     *
     * <p>This is offered as an optimization. If you know in advance the number
     * of pages you will need to support or have lazy-loading mechanisms in place
     * on your pages, tweaking this setting can have benefits in perceived smoothness
     * of paging animations and interaction. If you have a small number of pages (3-4)
     * that you can keep active all at once, less time will be spent in layout for
     * newly created view subtrees as the user pages back and forth.</p>
     *
     * <p>You should keep this limit low, especially if your pages have complex layouts.
     * This setting defaults to 1.</p>
     *
     * @param limit How many pages will be kept offscreen in an idle state.
     */
    public void setOffscreenPageLimit(int limit) {
        if (limit < DEFAULT_OFFSCREEN_PAGES) {
            Log.w(TAG, "Requested offscreen page limit " + limit + " too small; defaulting to " +
                    DEFAULT_OFFSCREEN_PAGES);
            limit = DEFAULT_OFFSCREEN_PAGES;
        }
        if (limit != mOffscreenPageLimit) {
            mOffscreenPageLimit = limit;
            populate();
        }
    }