本文介绍了getItem调用了两次,这导致tab1和tab2都在FragmentPagerAdapter中执行的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个滑动选项卡,其中有三个选项卡的三个不同片段.FragmentPagerAdapter中的getItem方法被调用了两次.我的第一个选项卡加载本地数据,并且布局与后两个选项卡(tab2,tab3)不同.Tab2和Tab3从服务器获取数据并相应地加载.

I have a swipe tab with three different fragments for three tabs. getItem method in FragmentPagerAdapter called twice. My first tab loads local data and have different layout than next two tabs (tab2, tab3). Tab2 and Tab3 fetches data from server and load accordingly.

我的问题是,第一次加载两次调用getItem,这会导致tab1和tab2都执行.尽管tab1仅包含本地数据,但是由于两次调用tab2并从服务器获取数据而执行.

My problem is, for first time loading getItem called twice and this causes tab1 and tab2 both executed. Though tab1 only consist local data but because of twice calling tab2 executed and fetch data from server.

我不想在tab1等中执行tab2及其功能.

I don't want to execute tab2 and it's functionality while I'm in tab1 and so forth.

getItem()代码:

@Override public Fragment getItem(int position) {
    Fragment fragment = null;
    switch (position) {
        case 0: fragment = new CommentFragment(); break;
        case 1: fragment = new AllPostFragment(); break;
        case 2: fragment = new TodayFragment(); break;
    }
    return fragment;
}

因此,我正在寻找解决方案.如果可以的话,请帮帮我.

So, I'm looking for a solution. Please help me out if you can.

推荐答案

在ViewPager中,ViewPager将加载多少个屏幕(片段)是有限制的.您可以通过调用ViewPagers setOffscreenPageLimit方法进行设置.

In ViewPager there is a limit how many screens (Fragments) your ViewPager will load. You can set this by calling ViewPagers setOffscreenPageLimit method.

但是,如果您检查 ViewPagers代码,它告诉您必须至少加载1个屏幕外页面:

HOWEVER if you inspect the ViewPagers code, it tells you that you must atleast load 1 offscreen page:

private static final int DEFAULT_OFFSCREEN_PAGES = 1;

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;
    }
    // ...
}

底线:对不起,我认为您只能加载当前的片段.

Bottom line: I don't think you can load the current Fragment only, sorry.

但是,如果您只想在用户可见分片时才可以从网络中加载数据,则可以在分片中执行类似的操作:

But you can do something like this in your Fragments if you want to load, lets say, data from network only when Fragments comes visible to user:

@Override
public void setUserVisibleHint(boolean isVisibleToUser) {
    super.setUserVisibleHint(isVisibleToUser);
    if (isVisibleToUser) {
        // Fetch data or something...
    }
}

这篇关于getItem调用了两次,这导致tab1和tab2都在FragmentPagerAdapter中执行的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!

07-18 18:52