循环FragmentPagerAdapter

时间:2012-04-20 13:22:11

标签: android android-viewpager

我有一个FragmentPagerAdapter可以正常工作,但我想知道的是,如果FragmentPagerAdapter在最后一个视图中,我怎么能让它循环回到第一个视图并继续正常

这是我正在使用的示例代码

public class FragmentPager extends FragmentActivity {
MyAdapter mAdapter;
ViewPager mPager;
static final int NUM_ITEMS = 5;

@Override
protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.main);

    mAdapter = new MyAdapter(getSupportFragmentManager());

    mPager = (ViewPager)findViewById(R.id.pager);
    mPager.setAdapter(mAdapter);
}

public static class MyAdapter extends FragmentPagerAdapter {
    public MyAdapter(FragmentManager fm) {
        super(fm);
    }

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

    @Override
    public Fragment getItem(int position) {
        return MyFragment.newInstance(position);
    }
}

public static class MyFragment extends ListFragment{
    int mNum;

    /**
     * Create a new instance of CountingFragment, providing "num"
     * as an argument.
     */
    static MyFragment newInstance(int num) {
        MyFragment f = new MyFragment();

        // Supply num input as an argument.
        Bundle args = new Bundle();
        args.putInt("num", num);
        f.setArguments(args);

        return f;
    }

    /**
     * When creating, retrieve this instance's number from its arguments.
     */
    @Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        mNum = getArguments() != null ? getArguments().getInt("num") : 1;
    }

    /**
     * The Fragment's UI is just a simple text view showing its
     * instance number.
     */
    @Override
    public View onCreateView(LayoutInflater inflater, ViewGroup container,
            Bundle savedInstanceState) {
        View v = inflater.inflate(R.layout.fragment_pager_list, container, false);
        View tv = v.findViewById(R.id.text);
        ((TextView)tv).setText("Fragment #" + mNum);
        return v;
    }

    @Override
    public void onActivityCreated(Bundle savedInstanceState) {
        super.onActivityCreated(savedInstanceState);
        setListAdapter(new ArrayAdapter<String>(getActivity(),
                android.R.layout.simple_list_item_1, new String[] {"test1","test2","test3","test4","Test5"}));
    }

    @Override
    public void onListItemClick(ListView l, View v, int position, long id) {
        Log.i("FragmentList", "Item clicked: " + id);
    }
}

}

基本上当它到达最后我怎么能让它显示第一个片段,因为它会转到任何其他片段?

即。 A->B,       B->CC->A和向后A->CC->BB->A

3 个答案:

答案 0 :(得分:2)

这是我的解决方案我有“n”个屏幕(在这种情况下为5个),因为我想回到列表末尾的第一个屏幕,我“添加另一个屏幕”,这只是一个精确的副本在最后一个屏幕上也是这样做的反向。基本上我现在有“n”屏+2(在这种情况下现在是7)。屏幕设置如copy of CABCcopy of A然后我设置一个手势监听器来监视某些页面上的滑动。

如果在列表的末尾(“A的副本”)并且我检测到向左滑动> a certain number of pixels,我将移至页面A并继续在正常页面旋转中向后滑动。

向相反方向滑动也是如此。

<强>问题

当从一个结束页面移动到模拟循环时,它确实有点慢,因为ViewPager加载了您当前所在页面之前和之后的页面但是因为您处于结束或开始时页面列表它不像通常那样加载下一页,因为技术上没有下一页。只有当每个列表行都有复杂的自定义视图时才会发生这种情况

您无法将此动画用于页面滚动,因为它不会看起来无缝,并且当您从复制的页面移动到实际页面(即A到A的副本)时会动画。

此外,它似乎有时卡在页面的末尾,我不知道为什么

这是我基于android开发者网站上的viewpager示例的完整演示应用程序

public class FragmentPager extends FragmentActivity{
MyAdapter mAdapter;
public static ViewPager mPager;
static int currentPage = 1;
static final int NUM_ITEMS = 7;
public static View vContainer;
float dxInitial=0;

@Override
protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.main);

    mAdapter = new MyAdapter(getSupportFragmentManager());

    mPager = (ViewPager)findViewById(R.id.pager);
    mPager.setAdapter(mAdapter);
    mPager.setCurrentItem(1,false);

    mPager.setOnTouchListener(new OnTouchListener(){

        @Override
        public boolean onTouch(View v, MotionEvent event) {


            if(event.getAction() == MotionEvent.ACTION_DOWN){
                dxInitial=event.getX();
                Log.d("INITIAL X", String.valueOf(dxInitial));
            }else if(event.getAction() == MotionEvent.ACTION_MOVE){
                if(event.getX() - dxInitial > 100 && currentPage==1){
                    mPager.setCurrentItem(6,false);
                }else if(dxInitial - event.getX() > 100 && currentPage==5){
                    mPager.setCurrentItem(0,false);
                }else if(dxInitial - event.getX() > 50 && currentPage==6){
                    mPager.setCurrentItem(1,false);
                }else if(event.getX() - dxInitial > 50 && currentPage==0){
                    mPager.setCurrentItem(5,false);
                }
            }

            /*if(Math.abs(dx) > Math.abs(dy)) {
                if(dx>75){ directiion = "right";
                }else if{
                    direction = "left";
                }
            } else {
                if(dy>0) direction = "down";
                else direction = "up";
            }*/

            return false;
        }

    });
    mPager.setOnPageChangeListener(new OnPageChangeListener(){

        @Override
        public void onPageScrollStateChanged(int state) {
            // TODO Auto-generated method stub
            if(state == ViewPager.SCROLL_STATE_IDLE){

            }
        }

        @Override
        public void onPageScrolled(int position, float positionOffset, int positionOffsetPixels) {

        }

        @Override
        public void onPageSelected(int arg0) {
            currentPage=arg0;

        }

    });
}

public static class MyAdapter extends FragmentPagerAdapter{
    public MyAdapter(FragmentManager fm) {
        super(fm);
    }

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

    @Override
    public Fragment getItem(int position) {
        return MyFragment.newInstance(position);
    }

    @Override
    public Object instantiateItem(View container, int position) {
        vContainer=container;
        return super.instantiateItem(container, position);

    }
}

public static class MyFragment extends ListFragment{
    int mNum;

    /**
     * Create a new instance of CountingFragment, providing "num"
     * as an argument.
     */
    static MyFragment newInstance(int num) {
        MyFragment f = new MyFragment();

        // Supply num input as an argument.
        Bundle args = new Bundle();
        args.putInt("num", num);
        f.setArguments(args);

        return f;
    }

    /**
     * When creating, retrieve this instance's number from its arguments.
     */
    @Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        mNum = getArguments() != null ? getArguments().getInt("num") : 1;
    }

    /**
     * The Fragment's UI is just a simple text view showing its
     * instance number.
     */
    @Override
    public View onCreateView(LayoutInflater inflater, ViewGroup container,
            Bundle savedInstanceState) {
        View v = inflater.inflate(R.layout.fragment_pager_list, container, false);
        View tv = v.findViewById(R.id.text);
        if(mNum == 6){
            mNum=1;
        }else if(mNum==7){
            mNum=5;
        }else if(mNum==0){
            mNum=5;
        }
        ((TextView)tv).setText("Fragment #" + mNum);
        return v;
    }

    @Override
    public void onActivityCreated(Bundle savedInstanceState) {
        super.onActivityCreated(savedInstanceState);
        setListAdapter(new ArrayAdapter<String>(getActivity(),
                android.R.layout.simple_list_item_1, new String[] {"test1","test2","test3","test4","Test5"}));
    }

    @Override
    public void onListItemClick(ListView l, View v, int position, long id) {
        Log.i("FragmentList", "Item clicked: " + id);
    }
}

}

答案 1 :(得分:1)

这是一个非常黑客,但对我来说它的效果非常好:

@Override
public int getCount() {
    return NUM_ITEMS * 1000;
}

这将使您的网页“循环”1000x 不要忘记在getItem上使用%operation,就像这样

@Override
public Fragment getItem(int position) {
    position = position % 1000;
    return MyFragment.newInstance(position);
}

答案 2 :(得分:0)

我根据tyczj的回答做了一个Kotlin解决方案,该解决方案处理在创建适配器后加载轮播项目的时间(例如,从服务器加载项目),并且不抓取触摸侦听器,而是等待空闲ViewPager2的状态。就我而言,我有一个“用户个人资料”轮播。

根据tycjz的回答,如果我们有一组项A B C D,则ViewPager2在功能上以C A B C D A结尾,但我们在位置1而不是0处开始ViewPager2,因此它最终在A上。

inner class UserProfileSlidePagerAdapter(fa: FragmentActivity) : FragmentStateAdapter(fa) {

    var profileToJumpTo: Int? = null

    override fun getItemCount(): Int {
        if (userIdsForLocalUsers.size > 0) {
            return userIdsForLocalUsers.size + 2
        }
        return userIdsForLocalUsers.size
    }

    override fun createFragment(position: Int): Fragment {
        var positionToUse = position - 1
        if (position > userIdsForLocalUsers.size)
        {
            positionToUse = 0
        }
        if (positionToUse < 0)
        {
            positionToUse = userIdsForLocalUsers.size - 1
        }
        val userId = userIdsForLocalUsers[positionToUse]
        this@ProfileViewModel.availableUserProfilesHash[userId].let {userProfile ->
            return CarouselUserProfileFragment.newInstance(userProfile!!)
        }
    }
}

在按如下方式管理PageAdapter的“ off by 1”定位问题后,可以确定发生ViewPager2 onPageSelected事件时是处于循环的开始还是结束,然后选择哪个页面页面处于onPageScrollStateChanged的空闲状态时跳转至。 因此,在存在ViewPager2的Fragment中:

this.profiles_view_pager.registerOnPageChangeCallback(object: ViewPager2.OnPageChangeCallback() {
    override fun onPageScrollStateChanged(state: Int) {
        if (state == ViewPager2.SCROLL_STATE_IDLE) {
            val adapter = this@CarouselFragment.profiles_view_pager.adapter as ProfileViewModel.UserProfileSlidePagerAdapter
            val profileToJumpTo = adapter.profileToJumpTo
            profileToJumpTo?.let {
                this@CarouselFragment.profiles_view_pager.setCurrentItem(profileToJumpTo, false)
                adapter.profileToJumpTo = null
            }
        }
        super.onPageScrollStateChanged(state)
    }
    override fun onPageSelected(position: Int) {
        val adapter = this@CarouselFragment.profiles_view_pager.adapter as ProfileViewModel.UserProfileSlidePagerAdapter
        adapter.itemCount.let { itemCount ->
            if (position == 0) {
                adapter.profileToJumpTo = itemCount - 2
            }
            if (position == itemCount - 1) {
                adapter.profileToJumpTo = 1
            }
        }
        super.onPageSelected(position)
    }
})

我还观看了LiveData,将当前项目设置为“ +1”。

this.profileViewModel.loadUserProfilesResult.observe(viewLifecycleOwner, Observer {     
    this.profiles_view_pager.setCurrentItem(1, false)
 })