Circular ViewPager. Fragments don't work as they supposed to after first round

前端 未结 1 921
逝去的感伤
逝去的感伤 2021-01-04 12:30

Ok, so i needed circular ViewPager. I was having really hard time to implement it. Now that i have implemented it and it is working fine as far as circular scroll is concern

1条回答
  •  粉色の甜心
    2021-01-04 12:39

    I've created a simple test-app with you PagerAdapter and simple Fragments with a Button:

    And it works fine!

    I've uploaded the source code here, so you can check it out and see if there's any difference with yours.

    As a Fragment's I used:

    public class FragmentA extends android.support.v4.app.Fragment {
    
        @Nullable
        @Override
        public View onCreateView(LayoutInflater inflater, @Nullable ViewGroup container, @Nullable Bundle savedInstanceState) {
            View rootView = inflater.inflate(R.layout.fragment_a, container, false);
            rootView.findViewById(R.id.button).setOnClickListener(new View.OnClickListener() {
                @Override
                public void onClick(View v) {
                    Snackbar.make(v, "Hi, fragment A", Snackbar.LENGTH_SHORT).show();
                }
            });
            return rootView;
        }
    }
    

    So what I can recommend

    • replace your fragments with some dummy ones (like the one above). If it works - the issue is in the Fragment code, not in the Circular ViewPager

    • If it still doesn't work - I'd try to instead of re-creating fragments multiple times - create them once and store:

       public class PagerAdapter extends FragmentPagerAdapter {
          Context mcontext;
          Fragment [] fragments;
          public PagerAdapter(FragmentManager fm, Context context, Fragment [] fragments) {
              super(fm);
              mcontext = context;
              this.fragments = fragments;
          }
      
          @Override
          public Fragment getItem(int position) {
              return fragments[position];
          }
      
          @Override
          public int getCount() {
              return fragments.length;
          }
      }
      

      And in Activity:

      Fragment[] fragments = {
              Fragment.instantiate(this, FragmentC.class.getName()),
              Fragment.instantiate(this, FragmentA.class.getName()),
              Fragment.instantiate(this, FragmentB.class.getName()),
              Fragment.instantiate(this, FragmentC.class.getName()),
              Fragment.instantiate(this, FragmentA.class.getName()),
      };
      .....
      viewPager.setAdapter(new PagerAdapter(getSupportFragmentManager(), this, fragments));
      

    Let me know, if it helps!

    0 讨论(0)
提交回复
热议问题