ViewPager正在执行错误的片段

时间:2018-02-11 16:45:58

标签: android android-fragments android-viewpager

我的ViewPager有问题。我正在使用自定义ImageButtons在片段之间滑动。问题是,当我尝试从第三个片段滑动到第四个(案例3)片段时,执行第五个(案例4)片段(没有片段UI),然后显示第四个片段。感谢

private class ScreenSlidePagerAdapter extends FragmentStatePagerAdapter {

        public ScreenSlidePagerAdapter(FragmentManager fm) {
            super(fm);
        }

        @Override
        public Fragment getItem(int position) {
            switch (position) {
                case 0: return ScreenSlidePageJobTitle.newInstance();
                case 1: return ScreenSlidePageJobDescription.newInstance();
                case 2: return ScreenSlidePageJobLocation.newInstance();
                case 3: return ScreenSlidePageJobPrice.newInstance();
                case 4: return ScreenSlidePageJobToDb.newInstance();
                default: return ScreenSlidePageJobToDb.newInstance();
            }
        }

        @Override
        public int getCount() {
            return NUM_PAGES;
        }
    }

    public void setSlide(int slide, boolean scroll) {
        mViewPager.setCurrentItem(slide, scroll);
    }

    public int getItem() {
        return mViewPager.getCurrentItem();
    }
}

我正在使用此功能进行滑动

nextButton.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                if(checkLocation())
                {
                    int slide = ((AddItemFragment)(getParentFragment())).getItem() + 1;
                    ((AddItemFragment)(getParentFragment())).setSlide(slide, true);
                }
            }
        });

//编辑 mViewPager被声明为全局变量并在onCreateView

中定义
public View onCreateView(LayoutInflater inflater, ViewGroup container,
                             Bundle savedInstanceState) {
        View rootView = inflater.inflate(R.layout.fragment_add_item, container, false);

        mViewPager = rootView.findViewById(R.id.add_item_view_pager);
        mViewPager.setAdapter(new ScreenSlidePagerAdapter(getChildFragmentManager()));

        SharedPreferences sharedPreferences = getContext().getSharedPreferences(JOB_PREFERENCES, Context.MODE_PRIVATE);


        return rootView;
    }

2 个答案:

答案 0 :(得分:1)

默认情况下,ViewPager会在当前片段的任一侧保留1个片段。查看https://developer.android.com/reference/android/support/v4/view/ViewPager.html#setOffscreenPageLimit(int)

答案 1 :(得分:0)

试试这段代码:

viewpager.setOffscreenPageLimit(4);

此代码可以解决您的问题。