如何一次加载一个viewpager选项卡

时间:2017-08-21 06:57:49

标签: android android-viewpager

如何一次加载一个viewpager选项卡?

我想用相同类型的Fragments开发动态Tabs。但问题是ViewPager在时间加载2个标签,当我在一个片段中更改一些数据时,它将反映每个片段。enter image description here

2 个答案:

答案 0 :(得分:0)

您可以在片段内覆盖此方法,如果此片段位于屏幕前方

,则会返回 true
 @Override
    public void setUserVisibleHint(boolean isVisibleToUser) {
        super.setUserVisibleHint(isVisibleToUser);
        if(isVisibleToUser){
            //You can do inside this method
        }
    }

}

答案 1 :(得分:0)

您可以使用yourViewPager.setOffScreenPageLimit(value)方法。但预加载页面的最小值 1 ,因此至少 1 页面将始终被缓存。

要将正确的数据设置为viewPager的页面,您可以执行以下操作:

public class YourFragment extends Fragment{
static final String ARGUMENT_PAGE_NUMBER = "arg_page_number";
int pos;

static YourFragment newInstance(int page) {
    YourFragment yourFragment = new YourFragment();
    Bundle arguments = new Bundle();
    arguments.putInt(ARGUMENT_PAGE_NUMBER, page);
    yourFragment.setArguments(arguments);
    //save fragment position
    return yourFragment;
}

@Override
public void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
        pos = getArguments().getInt(ARGUMENT_PAGE_NUMBER);
        //now you have position of this fragment
}
@Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
                         Bundle savedInstanceState) {
    View yourView = inflater.inflate(R.layout.your_fragment_layout, container, false);
   //use position of the fragment you received in onCreate to set up your views
    return yourView;
}