put below class in your android projects.

NOTE: This adapter for connect fragment in viewpager and tab layout in android.

				
					package com.example.adapter;

import androidx.annotation.NonNull;
import androidx.fragment.app.Fragment;
import androidx.fragment.app.FragmentManager;
import androidx.fragment.app.FragmentPagerAdapter;

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

public class ViewPagerAdapter extends FragmentPagerAdapter {

    ArrayList titleList = new ArrayList<>();
    List fragment = new ArrayList<>();

    public void addFragment(String title, Fragment fragment) {
        this.titleList.add(title);
        this.fragment.add(fragment);
    }

    public ViewPagerAdapter(FragmentManager fm) {
        super(fm);
    }

    @NonNull
    @Override
    public Fragment getItem(int position) {
        return fragment.get(position);
    }

    @Override
    public int getCount() {
        return titleList.size();
    }

    public CharSequence getPageTitle(int position) {
        return titleList.get(position);
    }

}
				
			

How to call adapter

				
					ViewPagerAdapter adapter = new ViewPagerAdapter(getSupportFragmentManager);

adapter.addFragment("Tab 1", new Tab1Fragment());

adapter.addFragment("Tab 2", new Tab2Fragment());

...... infinity......

yourViewPager.setAdapter(adapter);
				
			

Leave a Reply

Your email address will not be published. Required fields are marked *

One reply on “Viewpager Adapter in android java”

  • April 8, 2024 at 6:03 am

    Your point of view caught my eye and was very interesting. Thanks. I have a question for you.