1

I have MyViewPager2 adapter with four Fragments and a SemesterFragment that contain recyclerview on it DepartmentRVAdapter. onItem click in the recycler view i want to move to the respective fragment in viewpager2


How can i achieve the below description?

  • (onItem click on 0 pos) computer science department --->then load fragments(sem1,sem2,sem3,sem4) in a viewpager2 else if
  • (onItem click on 1 pos) statistic department --->then load fragments(sem1,sem2,sem3,sem4) in a viewpager2
  • e.t.c

below Is what I have, the code Is more focused now.Thanks

MainActivity.Java

package com.example.viewpager2;

import android.os.Bundle;
import androidx.appcompat.app.AppCompatActivity;
import androidx.fragment.app.FragmentManager;
import androidx.fragment.app.FragmentTransaction;

public class MainActivity extends AppCompatActivity {
    FragmentManager fragmentManager;
    FragmentTransaction fragmentTransaction;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);

        fragmentManager = getSupportFragmentManager();
        fragmentTransaction = fragmentManager.beginTransaction();
        fragmentTransaction.add(R.id.frameLayout,new DepartmentFragment());
        fragmentTransaction.commit();
    }
}

DepartmentFragment.java

package com.example.viewpager2;

import android.os.Bundle;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.Toast;
import androidx.fragment.app.Fragment;
import androidx.recyclerview.widget.LinearLayoutManager;
import androidx.recyclerview.widget.RecyclerView;
import java.util.ArrayList;
import java.util.List;

public class DepartmentFragment extends Fragment implements ClickInterface {
    List<DepartmentModel> mData;
    DepartmentRVAdapter adapter;
    RecyclerView recyclerView;

    public DepartmentFragment() {

    }
    @Override
    public View onCreateView(LayoutInflater inflater, ViewGroup container,
                             Bundle savedInstanceState) {
       View view = inflater.inflate(R.layout.fragment_start,container,false);
        recyclerView = view.findViewById(R.id.recyclerView);

        mData = new ArrayList<>();
        LinearLayoutManager linearLayoutManager = new LinearLayoutManager(getContext());
        recyclerView.setLayoutManager(linearLayoutManager);
        adapter = new DepartmentRVAdapter(mData,getContext(),this, DepartmentFragment.this);

//list of departments in the school
        mData.add(new DepartmentModel("Computer Science",R.drawable.glogo));
        mData.add(new DepartmentModel("Statistic",R.drawable.horse));

        recyclerView.setAdapter(adapter);
        return view;
    }
    //here implement interface class methods
    @Override
    public void onItemClickListener(int position) {
        Toast.makeText(getContext(),"clicked " + mData.get(position).getDepName(), Toast.LENGTH_LONG).show();

    }
    @Override
    public void onItemLongClickListener(int position) {

    }
}

DepartmentRVAdapter.Java

package com.example.viewpager2;

import android.content.Context;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.ImageView;
import android.widget.TextView;
import androidx.annotation.NonNull;
import androidx.recyclerview.widget.RecyclerView;
import java.util.List;
import java.util.Objects;

public class DepartmentRVAdapter extends RecyclerView.Adapter<DepartmentRVAdapter.MyViewHolder> {

    List<DepartmentModel> mData;
    LayoutInflater inflater;
    Context context;
    ClickInterface clickInterface;
    DepartmentFragment schoolFragment;

    public DepartmentRVAdapter(List<DepartmentModel> mData, Context context, ClickInterface clickInterface, DepartmentFragment sf) {
        this.mData=mData;
        this.context=context;
        this.clickInterface=clickInterface;
        schoolFragment =sf;
    }

    @NonNull
    @Override
    public MyViewHolder onCreateViewHolder(@NonNull ViewGroup parent, int viewType) {
        inflater = LayoutInflater.from(parent.getContext());
        View view = inflater.inflate(R.layout.row_department_xml,parent,false);
        MyViewHolder vh = new MyViewHolder(view);
        return vh;
    }

    @Override
    public void onBindViewHolder(@NonNull MyViewHolder holder, int position) {
        holder.imgDepLogo.setImageResource(mData.get(position).getDepLogo());
        holder.tvDepName.setText(mData.get(position).getDepName());
    }

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

    public class MyViewHolder extends RecyclerView.ViewHolder{
        ImageView imgDepLogo;
        TextView tvDepName;

        public MyViewHolder(@NonNull View itemView) {
            super(itemView);

            imgDepLogo = itemView.findViewById(R.id.imgDeptLogo);
            tvDepName = itemView.findViewById(R.id.tvDepName);

            tvDepName.setOnClickListener(new View.OnClickListener() {
                @Override
                public void onClick(View v) {
                   clickInterface.onItemClickListener(getLayoutPosition());

                 switch (getAdapterPosition()){
                        //loads department best on the position that user click
                        case 0:
                        // it loads all departments in the school
                          Objects.requireNonNull(schoolFragment.getActivity()).getSupportFragmentManager()
                                  .beginTransaction()
//                                  .setCustomAnimations(R.anim.slide_in_left,R.anim.exit_to_right)
                                  .replace(R.id.frameLayout,new SemesterFragment())
                                  .addToBackStack(null).
                                  commit();
                            break;
                            case 1:
                            // it loads all departments in the school
                                Objects.requireNonNull(schoolFragment.getActivity()).getSupportFragmentManager()
                                        .beginTransaction()
                                       // .setCustomAnimations(R.anim.slide_in_left,R.anim.exit_to_left,R.anim.enter_from_right,R.anim.exit_to_left)
                                        .replace(R.id.frameLayout,new SemesterFragment())
                                        .addToBackStack(null).
                                        commit();
                        break;
                    }
                }
            });
        }
    }
}

SemesterFragment.Java

package com.example.viewpager2;

import android.os.Bundle;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import androidx.annotation.NonNull;
import androidx.fragment.app.Fragment;
import androidx.viewpager2.widget.ViewPager2;
import com.google.android.material.tabs.TabLayout;
import com.google.android.material.tabs.TabLayoutMediator;

public class SemesterFragment extends Fragment{
    TabLayout tabLayout;
    ViewPager2 viewPager2;
    MyViewPager2 adapter;

    public SemesterFragment() {

    }
    @Override
    public View onCreateView(LayoutInflater inflater, ViewGroup container,
                             Bundle savedInstanceState) {
        View view = inflater.inflate(R.layout.fragment_semester, container, false);
        viewPager2 = (ViewPager2) view.findViewById(R.id.viewPager2);
        tabLayout = view.findViewById(R.id.tabLayout);

        adapter = new MyViewPager2(getChildFragmentManager(),this.getLifecycle());

        viewPager2.setAdapter(adapter);
        new TabLayoutMediator(tabLayout, viewPager2,
                new TabLayoutMediator.TabConfigurationStrategy() {
                    @Override
                    public void onConfigureTab(@NonNull TabLayout.Tab tab, int position) {
                        tab.setText("Sem" + (position + 1));
                    }
                }).attach();
        return view;
    }
}

RVFragment.java

package com.example.viewpager2;

import android.content.Context;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.TextView;
import androidx.annotation.NonNull;
import androidx.recyclerview.widget.RecyclerView;
import java.util.List;

public class RVFragment extends RecyclerView.Adapter<RVFragment.MyViewHolder> {
Context context;
List<SemesterModelClass> mData;

    public RVFragment(Context context, List<SemesterModelClass> mData) {
        this.context = context;
        this.mData = mData;
    }
    @NonNull
    @Override
    public MyViewHolder onCreateViewHolder(@NonNull ViewGroup parent, int viewType) {
        LayoutInflater inflater = LayoutInflater.from(parent.getContext());
        View view = inflater.inflate(R.layout.roww_xml,parent,false);
        MyViewHolder vh = new MyViewHolder(view);
        return vh;
    }
    @Override
    public void onBindViewHolder(@NonNull MyViewHolder holder, int position) {
        holder.tvCourseCode.setText(mData.get(position).getCourseCode());
        holder.tvCourseTitle.setText(mData.get(position).getCourseTitle());
        holder.tvCreditUnit.setText(mData.get(position).getCreditUnit());
    }
    @Override
    public int getItemCount() {
        return mData.size();
    }

    public class MyViewHolder extends RecyclerView.ViewHolder{
        TextView tvCourseCode;
        TextView tvCourseTitle;
        TextView tvCreditUnit;
        public MyViewHolder(@NonNull View itemView) {
            super(itemView);
            tvCourseCode = itemView.findViewById(R.id.tvCourseCode);
            tvCourseTitle = itemView.findViewById(R.id.tvCourseTitle);
            tvCreditUnit = itemView.findViewById(R.id.tvCreditUnit);
        }
    }
}

MyViewPager2.java

package com.example.viewpager2;

import androidx.annotation.NonNull;
import androidx.fragment.app.Fragment;
import androidx.fragment.app.FragmentManager;
import androidx.lifecycle.Lifecycle;
import androidx.viewpager2.adapter.FragmentStateAdapter;

public class MyViewPager2  extends FragmentStateAdapter {

    public MyViewPager2(@NonNull FragmentManager fragmentManager, @NonNull Lifecycle lifecycle) {
        super(fragmentManager, lifecycle);
    }

    @NonNull
    @Override
    public Fragment createFragment(int position) {

        switch (position){

            case 0: return FirstSemesterFragment.newInstance("first frag instance");
            case 1: return  SecondSemesterFragment.newInstance("second frag instance");
            case 2: return ThirdSemesterFragment.newInstance("third frag instance");
            case 3: return FourthSemesterFragment.newInstance("fourth frag instance");
            default: return FirstSemesterFragment.newInstance("first frag instance");
        }
    }
    @Override
    public int getItemCount() {
        return 4;
    }
}

FirstSemesterFragment.Java

package com.example.viewpager2;

import android.os.Bundle;
import androidx.fragment.app.Fragment;
import androidx.recyclerview.widget.LinearLayoutManager;
import androidx.recyclerview.widget.RecyclerView;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.TextView;    
import java.util.ArrayList;
import java.util.List;

public class FirstSemesterFragment extends Fragment {

    List<SemesterModelClass> mData;
    RVFragment adapter;
    RecyclerView recyclerView;

    private View view;

    public FirstSemesterFragment() {
        // Required empty public constructor
    }

    @Override
    public View onCreateView(LayoutInflater inflater, ViewGroup container,
                             Bundle savedInstanceState) {

        view = inflater.inflate(R.layout.fragment, container, false);
        recyclerView = view.findViewById(R.id.recyclerView);

        mData = new ArrayList<>();
        LinearLayoutManager layoutManager = new LinearLayoutManager(getContext());
        recyclerView.setLayoutManager(layoutManager);
        adapter = new RVFragment(getContext(),mData);

        //this infaltes first semester fragment, viewpager2
        for (int i = 0; i < SemesterDataClass.courseCode1.length; i++) {
            mData.add(new SemesterModelClass(
                    SemesterDataClass.courseCode1[i],
                    SemesterDataClass.courseTitle1[i],
                    SemesterDataClass.creditUnit1[i]));
        }
        recyclerView.setAdapter(adapter);
        return view;
    }
    public static FirstSemesterFragment newInstance(String text) {
        // i did not use this parameter
        Bundle args = new Bundle();
        FirstSemesterFragment fragment = new FirstSemesterFragment();
        args.putString("text",text);
        fragment.setArguments(args);

        return fragment;
    }
}

SecondSemesterFragment.Java

package com.example.viewpager2;

import android.os.Bundle;

import androidx.fragment.app.Fragment;
import androidx.recyclerview.widget.LinearLayoutManager;
import androidx.recyclerview.widget.RecyclerView;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import java.util.ArrayList;
import java.util.List;

public class SecondSemesterFragment extends Fragment {
    List<SemesterModelClass> mData;
    RVFragment adapter;
    RecyclerView recyclerView;

    View view;
    public SecondSemesterFragment() {
        // Required empty public constructor
    }

    @Override
    public View onCreateView(LayoutInflater inflater, ViewGroup container,
                             Bundle savedInstanceState) {

        view =  inflater.inflate(R.layout.fragment, container, false);
        recyclerView = view.findViewById(R.id.recyclerView);

        mData = new ArrayList<>();
        LinearLayoutManager layoutManager = new LinearLayoutManager(getContext());
        recyclerView.setLayoutManager(layoutManager);
        adapter = new RVFragment(getContext(),mData);

        //this inflates second semester fragment, viewpager2
        for (int i = 0; i < SemesterDataClass.courseCode2.length; i++) {
            mData.add(new SemesterModelClass(
                    SemesterDataClass.courseCode2[i],
                    SemesterDataClass.courseTitle2[i],
                    SemesterDataClass.creditUnit2[i]));
        }
        recyclerView.setAdapter(adapter);
        return  view;
    }
    public static SecondSemesterFragment newInstance(String text){
        // i did not use this parameter
        SecondSemesterFragment secondSemesterFragment = new SecondSemesterFragment();
        Bundle args = new Bundle();
        args.putString("text", text);
        secondSemesterFragment.setArguments(args);
        return secondSemesterFragment;
    }
}

ThirdSemesterFragment.java

package com.example.viewpager2;

import android.os.Bundle;
import androidx.fragment.app.Fragment;
import androidx.recyclerview.widget.LinearLayoutManager;
import androidx.recyclerview.widget.RecyclerView;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import java.util.ArrayList;
import java.util.List;

public class ThirdSemesterFragment extends Fragment {
    RVFragment adapter;
    RecyclerView recyclerView;
    List<SemesterModelClass> mData;

    View view;

    public ThirdSemesterFragment() {
        // Required empty public constructor
    }
    @Override
    public View onCreateView(LayoutInflater inflater, ViewGroup container,
                             Bundle savedInstanceState) {

        view = inflater.inflate(R.layout.fragment, container, false);
        recyclerView = view.findViewById(R.id.recyclerView);

        mData = new ArrayList<>();
        LinearLayoutManager layoutManager = new LinearLayoutManager(getContext());
        recyclerView.setLayoutManager(layoutManager);
        adapter = new RVFragment(getContext(),mData);

        //this inflates Third semester fragment, viewpager2
        for (int i = 0; i < SemesterDataClass.courseCode3.length; i++) {
            mData.add(new SemesterModelClass(
                    SemesterDataClass.courseCode3[i],
                    SemesterDataClass.courseTitle3[i],
                    SemesterDataClass.creditUnit3[i]));
        }
        recyclerView.setAdapter(adapter);
        return view;
    }
    public static ThirdSemesterFragment newInstance(String text){
        // i did not use this parameter
        ThirdSemesterFragment thirdSemesterFragment = new ThirdSemesterFragment();
        Bundle args = new Bundle();
        args.putString("msg",text);
        thirdSemesterFragment.setArguments(args);
        return thirdSemesterFragment;
    }
}

FourthSemesterFragment.java

package com.example.viewpager2;

import android.os.Bundle;
import androidx.fragment.app.Fragment;
import androidx.recyclerview.widget.LinearLayoutManager;
import androidx.recyclerview.widget.RecyclerView;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import java.util.ArrayList;
import java.util.List;

public class FourthSemesterFragment extends Fragment {
RVFragment adapter;
RecyclerView recyclerView;
List<SemesterModelClass> mData;

View view;
    public FourthSemesterFragment() {
        // Required empty public constructor
    }

    @Override
    public View onCreateView(LayoutInflater inflater, ViewGroup container,
                             Bundle savedInstanceState) {

        view =  inflater.inflate(R.layout.fragment, container, false);
        recyclerView = view.findViewById(R.id.recyclerView);

        mData = new ArrayList<>();
        LinearLayoutManager layoutManager = new LinearLayoutManager(getContext());
        recyclerView.setLayoutManager(layoutManager);
        adapter = new RVFragment(getContext(),mData);

        //this inflates Fourth semester fragment, viewpager2
        for (int i = 0; i < SemesterDataClass.courseCode4.length; i++) {
            mData.add(new SemesterModelClass(
                    SemesterDataClass.courseCode4[i],
                    SemesterDataClass.courseTitle4[i],
                    SemesterDataClass.creditUnit4[i]));
        }
        recyclerView.setAdapter(adapter);
        return view;
    }
    public static FourthSemesterFragment newInstance(String text) {
        // i did not use this parameter
        FourthSemesterFragment fourthSemesterFragment = new FourthSemesterFragment();
        Bundle agrs = new Bundle();
        agrs.putString("msg",text);
        fourthSemesterFragment.setArguments(agrs);
        return fourthSemesterFragment;
    }
}

SemesterDataClass.java

package com.example.viewpager2;

public class SemesterDataClass {
    //Semester One Computer science
    static String[] courseCode1 = {"COM 101","COM 112", "COM 113","STA 111","STA 112", "MTH 111","MTH 112","GNS 102","GNS 127"};
    static String[] courseTitle1 = {"Intro to computing","intro to dig. elcnics","intro to progmmng","Descriptive Sta.","Elmtry probability",
                                  "Logic & Linear Algebra","Func. & Geometry","Comm. in englisg 1","Citizenship edu 1"};
    static String[] creditUnit1 = {"4","4","4","3","3","2","3","2","2"};

    //Semester Two Computer science
    static String[] courseCode2 = {"COM 121","COM 122", "COM 123","COM 124","COM 125", "COM 126","GNS 128","GNS 202"};
    static String[] courseTitle2 = {"Progmg using ooJava","Intro to the internet","Comp app packages I","Data struc. & algorithms","intro to syst analysis",
                                  "PC upgrade & maintenance","Comm. in englisg 1","Citizenship edu II"};
    static String[] creditUnit2 = {"6","4","6","4","3","6","2","2"};

    //Semester Three Computer science
    static String[] courseCode3 = {"COM 211","COM 212", "COM 213","COM 214","COM 215", "COM 216","BAM 126"};
    static String[] courseTitle3 = {"Progmg using ooBasic","Intro to syst progrmm","Unified Modeling lang(uml)","Filel org & mgmt","Comp packages II",
                                 "Comp syst trouble shooting I","Intro to entrepreneurship"};
    static String[] creditUnit3 = {"5","5","5","3","6","5","4"};

    //Semester Fourth Computer science
    static String[] courseCode4 = {"COM 222","COM 223", "COM 224","COM 225","COM 226", "COM 229","BAM 216"};
    static String[] courseTitle4 = {" Intro to scientific Prog Java","Seminar on comp & society","Basic hardware maintenance","Mgt info syst","Web technology",
                                   "Comp syst trouble shooting II","Project","Practice of entrepreneurship"};
    static String[] creditUnit4 = {"6","2","5","4","6","5","4","3"};
}

activity_main.xml

<?xml version="1.0" encoding="utf-8"?> <LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"     xmlns:app="http://schemas.android.com/apk/res-auto"     xmlns:tools="http://schemas.android.com/tools"     android:layout_width="match_parent"     android:layout_height="match_parent"     android:orientation="vertical"     tools:context=".MainActivity">      <FrameLayout         android:layout_width="match_parent"         android:layout_height="match_parent"         android:id="@+id/frameLayout">      </FrameLayout>  </LinearLayout>

roww_xml.xml

<?xml version="1.0" encoding="utf-8"?> <LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"     android:layout_width="match_parent"     android:layout_height="wrap_content"     android:orientation="horizontal"     android:layout_marginTop="5dp">      <TextView         android:id="@+id/tvSn"         android:layout_width="wrap_content"         android:layout_height="wrap_content"         android:layout_marginTop="5dp"         android:paddingStart="5dp"         android:paddingLeft="5dp"         android:paddingRight="5dp"         android:text="@string/sn"         android:textSize="20sp"         android:textColor="@color/purple_200"/>      <TextView         android:id="@+id/tvCourseTitle"         android:layout_width="wrap_content"         android:layout_height="wrap_content"         android:layout_marginTop="5dp"         android:paddingStart="5dp"         android:paddingLeft="5dp"         android:paddingRight="5dp"         android:text="@string/coursetitle"         android:textSize="20sp" />      <TextView         android:id="@+id/tvCourseCode"         android:layout_width="wrap_content"         android:layout_height="wrap_content"         android:layout_marginTop="5dp"         android:paddingStart="5dp"         android:paddingLeft="5dp"         android:paddingRight="5dp"         android:text="@string/coursecode"         android:textSize="20sp" />      <TextView         android:id="@+id/tvCreditUnit"         android:layout_width="wrap_content"         android:layout_height="wrap_content"         android:layout_marginTop="5dp"         android:paddingStart="5dp"         android:paddingLeft="5dp"         android:paddingRight="5dp"         android:text="@string/creditunit"         android:textColor="@color/purple_500"         android:textSize="20sp" /> </LinearLayout>

fragment.xml

<?xml version="1.0" encoding="utf-8"?> <LinearLayout     xmlns:android="http://schemas.android.com/apk/res/android" android:layout_width="match_parent"     android:layout_height="match_parent"     android:orientation="vertical">      <androidx.recyclerview.widget.RecyclerView         android:layout_width="match_parent"         android:layout_height="match_parent"         android:layout_marginTop="5dp"         android:id="@+id/recyclerView"/> </LinearLayout>

Fragment_semester.xml

<?xml version="1.0" encoding="utf-8"?> <LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"     android:layout_width="match_parent"     android:layout_height="match_parent"     xmlns:tools="http://schemas.android.com/tools"     android:orientation="vertical"     tools:context=".SemesterFragment" >       <com.google.android.material.tabs.TabLayout         android:layout_width="match_parent"         android:layout_height="wrap_content"         android:id="@+id/tabLayout"/>      <androidx.viewpager2.widget.ViewPager2         android:layout_width="match_parent"         android:layout_height="match_parent"         android:id="@+id/viewPager2"/>  </LinearLayout>

fragment_start.xml

<?xml version="1.0" encoding="utf-8"?> <LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"     xmlns:tools="http://schemas.android.com/tools"     android:layout_width="match_parent"     android:layout_height="match_parent"     android:layout_marginTop="60dp"     tools:context=".DepartmentFragment"     android:id="@+id/start_container"     android:orientation="horizontal">      <androidx.recyclerview.widget.RecyclerView         android:layout_width="match_parent"         android:layout_height="match_parent"         android:id="@+id/recyclerView"/>  </LinearLayout>

frame_layout.xml

<?xml version="1.0" encoding="utf-8"?> <LinearLayout     xmlns:android="http://schemas.android.com/apk/res/android"     android:layout_width="match_parent"     android:layout_height="match_parent">      <FrameLayout         android:layout_width="match_parent"         android:layout_height="match_parent"         android:id="@+id/container_fragment">     </FrameLayout>   </LinearLayout>

row_department.xml

 <?xml version="1.0" encoding="utf-8"?> <LinearLayout     xmlns:android="http://schemas.android.com/apk/res/android"     android:layout_width="match_parent"     android:layout_height="wrap_content"     android:background="@color/white">      <ImageView         android:layout_width="80dp"         android:layout_height="80dp"         android:src="@drawable/ic_launcher_background"         android:paddingTop="10dp"         android:paddingLeft="10dp"         android:id="@+id/imgDeptLogo"         android:paddingStart="10dp"         android:paddingEnd="10dp"         android:paddingRight="10dp"         android:contentDescription="@string/todoo" />      <TextView         android:layout_width="match_parent"         android:layout_height="wrap_content"         android:text="@string/department"         android:id="@+id/tvDepName"         android:textSize="24sp"         android:layout_marginTop="20dp"         android:paddingLeft="10dp"         android:paddingStart="10dp"         android:paddingEnd="10dp"         />  
    </LinearLayout>
sir.p
  • 33
  • 6

2 Answers2

0

Are you asking how to inflate data into the fragments in the ViewPagers every time you click on the respective recycler view item? I'm so sorry, I don't get your question and I really want to help

  • yes of course u get It right. I want the recycler view to open It respective fragment with data loaded on It. As of my code I can iflate only for a particular fragment in the viewpager2. In this case I want to inflate the viewpager2 on each of the onItem click In recycler view but am stuck on the way – sir.p Apr 06 '21 at 06:15
  • You can use a custom fragment adapter with an array list of fragments in it. And everytime you click on the recycler view item, in the click listener you can add the new fragment object to the list view and notify the adapter when changes is made by calling notifyDataSetChanged(). Once this is done, a new fragment will be added to the view pager. If you want specific data in the fragment, you can use a constructor in the fragment and receive all the data from the activity and you can inflate the data in onViewCreated method of the fragment. I can send you sample codes if you want any. – SooryaSRajan Apr 06 '21 at 07:17
  • Yes, I want It, It will really help alot. Thanks – sir.p Apr 06 '21 at 08:17
  • Ok thanks, but is like your code does the same thing as mine, I think I should edit my code again – sir.p Apr 07 '21 at 06:23
  • You might need to do some changes. I'd be glad to help if you run into any problem doing so. Cheers – SooryaSRajan Apr 07 '21 at 12:34
0

This is the ViewPager adapter I used in one of my projects:

public class PageAdapter extends FragmentPagerAdapter {
public ArrayList<Fragment> fragments = new ArrayList<>();
public ArrayList<String> name = new ArrayList<>();

public PageAdapter(@NonNull FragmentManager fm, int behavior) {
    super(fm, behavior);
}

public void AddFragment(Fragment fragment, String name){
    fragments.add(fragment);
    this.name.add(name);
}

@Nullable
@Override
public CharSequence getPageTitle(int position) {
    return name.get(position);
}

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

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

}

And if you want to add a fragment to your ViewPager, you just use the following code:

private ViewPager viewPager;
private TabLayout tabLayout;

viewPager = findViewById(R.id.view_pager); //Your View Pager object
adapter = new PageEditorAdapter(getSupportFragmentManager(), 0); //Initialize Adapter
viewPager.setAdapter(adapter); //Configuring with adapter

tabLayout = findViewById(R.id.tab_layout);
tabLayout.setupWithViewPager(viewPager); //Tab Layout, if you're using any

//You can execute the below code in the onClick block of your Recycler Adapter to perform fragment addition to view pager when clicked

adapter.AddFragment(new YourFragment(FragmentData), "View Pager Title"); //Adds new fragment to View Pager
adapter.notifyDataSetChanged(); //Notifies the adapter that changes has been done to the list of fragments