3

我有一个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);
    }
}

}

基本上当它结束时,我怎样才能让它显示第一个片段,因为它会转到任何其他片段?

IE。A->B, B->C, C->A 和向后 A->C, C->B,B->A

4

3 回答 3

3

这是我的解决方案,我有“n”个屏幕(在这种情况下为 5 个),因为我想回到列表末尾的第一个屏幕,所以我“添加另一个屏幕”,这只是最后一个屏幕的精确副本屏幕并为相反方向执行此操作。基本上我现在有“n”个屏幕+2(在这种情况下是 7 个)。屏幕是这样设置的copy of C, A, B, Ccopy 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);
    }
}

}
于 2012-11-02T23:17:31.117 回答
1

这是一个很好的技巧,但对我来说它工作得很好:

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

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

@Override
public Fragment getItem(int position) {
    position = position % 1000;
    return MyFragment.newInstance(position);
}
于 2012-10-08T17:01:09.610 回答
0

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

根据 tycjz 的回答,如果我们有一组 items A B C D,那么 ViewPager2 在功能上以 结束C A B C D A,但我们在 ViewPager2 @位置 1 而不是 0 开始,所以它结束了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”定位问题后,您可以判断 ViewPager2onPageSelected事件发生时您是在循环的开始还是结束,然后选择页面在时跳转到哪个页面的空闲状态onPageScrollStateChanged。所以在FragmentViewPager2 存在的地方:

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)
 })
于 2020-06-17T19:31:44.467 回答