TabLayout+ViewPager2绑定FragmentStateAdapter

阅读 4

TabLayout+ViewPager2实现切换时 加载不同的 fragment

import android.os.Bundle;
import androidx.annotation.NonNull;
import androidx.fragment.app.Fragment;
import androidx.viewpager2.adapter.FragmentStateAdapter;

import java.util.ArrayList;
import java.util.List;

@SuppressWarnings("unused")
public class RgAdapter extends FragmentStateAdapter {

    private List<Class<?>> fragments;
    private List<Bundle> bundles;

    public RgAdapter(@NonNull Fragment fragment) {
        super(fragment);
        if (fragments == null) {
            fragments = new ArrayList<>();
        }
    }

    @SuppressWarnings("ConstantConditions")
    @NonNull
    @Override
    public Fragment createFragment(int position) {
        try {
            Fragment result = (Fragment)fragments.get(position).newInstance();
            if (bundles != null) {
                Bundle bundle = bundles.get(position);
                result.setArguments(bundle);
            }
            return result;
        } catch (IllegalAccessException | InstantiationException e) {
            e.printStackTrace();
            return null;
        }
    }

    @Override
    public int getItemCount() {
        return fragments.size();
    }

    public void addFragment(Fragment fragment) {
        if (!fragment.isAdded()) {
            fragments.add(fragment.getClass());
        }
    }

    public void addFragment(Fragment fragment, Bundle bundle) {
        addFragment(fragment);
        if (bundles == null) {
            bundles = new ArrayList<>();
        }
        bundles.add(bundle);
    }

    @Override
    public long getItemId(int position) {
        return super.getItemId(position);
    }
}

 

禁用 viewpager2 的预加载,使用懒加载以节省程序的加载。

各位看官,如果你觉得本文不错,请支持一下~