SoFunction
Updated on 2025-04-06

How to solve the problem of repeated loading of Fragment + Viewpager sliding page in Android development

Preface

Previously, when loading multiple Fragments on a Viewpager, the Fragmnet object that has been created will always be instantiated.

  (new FragmentPagerAdapter(getSupportFragmentManager()) {
      @Override
      public Fragment getItem(int position) {
        switch(position){
        case 0:
        fragments=new Fragmnet01();
        break;
          case 1:
        fragments=new Fragmnet02();
        break;
        .....
      }
        return fragments;
      }
      @Override
      public int getCount() {
        return ();
      }
    });

Actually, if you think about it carefully, this is very unreasonable. First of all, you are instantiating memory is a waste. In addition, Viewpager is preloadable. When we load a certain Fragmnet, it will load the left and right sides of it (exceptions at the beginning and end.) So to prevent repeated loading and wasting resources, we can use an object array to load fragments. Whenever the position is empty, we can load a layout specific code on that position.

//Define an array of objects and give a length fragments=new MyFragment[()];
    (new FragmentPagerAdapter(getSupportFragmentManager()) {
      @Override
      public Fragment getItem(int position) 
      {
      //Judge here if the current page of Fragmnet[position] is not loaded, we will load it on it again        if(fragments[position]==null){
          //Here is just writing a constructor to pass the value into the fragment          MyFragment my = ((position).getId());
          fragments[position]=my;
        }
        return fragments[position];
      }
      @Override
      public int getCount() {
        return ();
      }
    });

Of course, you can also use bundler to pass values ​​in fragment.

 public static MyFragment getInstance(int id){
    MyFragment myFragment=new MyFragment();
    Bundle bundle=new Bundle();
    ("id",id);
    (bundle);
    return myFragment;
  }

The above is the editor’s introduction to how to solve the problem of repeated loading of Fragment + Viewpager sliding page in Android development. I hope it will be helpful to everyone. If you have any questions, please leave me a message. The editor will reply to everyone in time!