1

I have created a RecyclerView and added cards in fragment.I want to open different activities by clicking on different cards in CardView.But I am only able to open the same activity for all the cards.I searched different answers in StackOverFlow.But I couldn't. could you tell me how to solve this issue...? If you can give full code,I'm happy.

Here are my codes...

PDFFragment.java

public class PDFFragment extends Fragment {

    View v;
    List<Pdf> listBook;

    public View onCreateView(@NonNull LayoutInflater inflater, @Nullable ViewGroup container, @Nullable Bundle savedInstanceState) {
        v= inflater.inflate(R.layout.fragment_pdf,container,false);
        listBook = new ArrayList<>();
        listBook.add(new Pdf("1-pdf name",R.drawable.pdf1image));
        listBook.add(new Pdf("2-pdf name",R.drawable.pdf2image));
        listBook.add(new Pdf("3-pdf name",R.drawable.pdf3image));
        listBook.add(new Pdf("4-pdf name",R.drawable.pdf4image);
        listBook.add(new Pdf("5-pdf name",R.drawable.pdf5image));
        listBook.add(new Pdf("6-pdf name",R.drawable.pdf6image));
        listBook.add(new Pdf("7-pdf name",R.drawable.pdf7image));

        RecyclerView myTV= (RecyclerView) v.findViewById(R.id.recyclerview_id);
        RecyclerViewAdapterPDF myAdapter = new RecyclerViewAdapterPDF(getActivity(),listBook);
//Part 1 -Start Changing number of columns
        myTV.setLayoutManager(new GridLayoutManager(getActivity(),calculateNoOfColumns(getActivity())));
//Part 1 -End Changing number of columns
        myTV.setAdapter(myAdapter);
        return v;
    }

    //Part 2 -Start Changing number of columns
    public int calculateNoOfColumns(Context context) {
        DisplayMetrics displayMetrics = context.getResources().getDisplayMetrics();
        float dpWidth = displayMetrics.widthPixels / displayMetrics.density;
        int noOfColumns = (int) (dpWidth / 120);
        return noOfColumns;
    }
    //Part 2 -End Changing number of columns
}

RecyclerViewAdapterPDF.java

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

    private Context mContext;
    private List<Pdf> mData;

    public RecyclerViewAdapterPDF(Context mContext, List<Pdf> mData) {
        this.mContext = mContext;
        this.mData = mData;
    }

    @Override
    public MyViewHolder onCreateViewHolder( ViewGroup parent, int viewType) {

        View view;
        LayoutInflater mInflater = LayoutInflater.from(mContext);
        view = mInflater.inflate(R.layout.cardview_item_pdf,parent,false);
        return new MyViewHolder(view);
    }

    @Override
    public void onBindViewHolder( MyViewHolder holder, int position) {
        holder.tv_book_title.setText(mData.get(position).getTitle());
        holder.img_book_thumbnail.setImageResource(mData.get(position).getPhoto());
    }

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

    public static class MyViewHolder extends RecyclerView.ViewHolder{

        TextView tv_book_title;
        ImageView img_book_thumbnail;

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

            tv_book_title = (TextView) itemView.findViewById(R.id.book_title_id);
            img_book_thumbnail = (ImageView) itemView.findViewById(R.id.book_image_id);
        }
     }
}

ViewPagerAdapter.java

public class ViewPagerAdapter extends FragmentPagerAdapter {


    private final List<Fragment> fragmentList = new ArrayList<>();
    private final List<String> FragmentListTitles = new ArrayList<>();

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

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

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

    @Nullable
    @Override
    public CharSequence getPageTitle(int position) {
        return FragmentListTitles.get(position);
    }
    public void AddFragment(Fragment fragment,String Title){
        fragmentList.add(fragment);
        FragmentListTitles.add(Title);
    }
}
Mr.Soft
  • 143
  • 2
  • 14

2 Answers2

5

You need a reference to your card on the view holder:

public static class MyViewHolder extends RecyclerView.ViewHolder{

        TextView tv_book_title;
        ImageView img_book_thumbnail;
        CardView cardview;

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

            tv_book_title = (TextView) itemView.findViewById(R.id.book_title_id);
            img_book_thumbnail = (ImageView) itemView.findViewById(R.id.book_image_id);
            cardview = itemView.findViewById(R.id.yourCardId);
        }
     }

And on the onBindViewHolder() you set a click listener responsible for opening the activity:

@Override
public void onBindViewHolder( MyViewHolder holder, int position) {
        holder.tv_book_title.setText(mData.get(position).getTitle());
        holder.img_book_thumbnail.setImageResource(mData.get(position).getPhoto());
        holder.cardView.setOnClickListener(new View.OnClickListener() {
                 public void onClick(View v) {
                    Intent intent;
                    switch (position) {
                        case 0:
                            intent = new Intent(mContext, pdfone.class);
                            mContext.startActivity(intent);
                            break;
                        case 1:
                            intent = new Intent(mContext, pdftwo.class);
                            mContext.startActivity(intent);
                            break;
                        ...
                        //do the same for every card possible
                   } 
                 }

}
user8886048
  • 109
  • 6
  • I want to add different activities for different cards.anyway thank you – Mr.Soft Aug 30 '18 at 16:05
  • "ThisPDFActivity.class" you mentioned one class only..I want to add more activity classes for each and every card. eg:ThisPDFActivity1.class, ThisPDFActivity2.class – Mr.Soft Aug 30 '18 at 17:07
  • Yes, you can do checks to know which card you have, and start the activity accordingly. How many cards you have and what are the actual names of your activities? I'll try to update my answer to help you with that – user8886048 Aug 30 '18 at 17:16
  • Now I have 10 cards.In future I'm going to add more cards...You can give me example then I can copy and paste code(hope you are using switch statement or if else statement).my class names are pdfone.class,pdftwo.class,pdfthree.class,pdffour.class and so on.... – Mr.Soft Aug 30 '18 at 17:26
  • Check the code now. That's basically what you have to do. And each time you add a new card, you add another case on the switch. If your classes were named like pdf1, pdf2 and etc you could use reflection, just like Ana showed in the other answer. – user8886048 Aug 30 '18 at 17:40
  • Now app running nicely.I accidentally changed one of id.Now it's OK.but there is a problem,..when click some cards,more pdf classes opening.I mean for some cards pdf1,pdf2 classes opening multiple times – Mr.Soft Aug 30 '18 at 18:35
  • Awesome bro...Code working 100%. please can you edit your answer please.Then another beginner also understand correctly.As well as change case 1 to case 0 .case 1 to case 2.otherwise first card not working.Thank you again for you time and kindness....Thanks – Mr.Soft Aug 30 '18 at 19:15
  • 1
    Fixed! Glad I could help :) – user8886048 Aug 30 '18 at 19:48
0

Use reflection like this

So in your case, something like:

String activityToStart = "com.pkg.pdf"+position;
    try {
        Class<?> c = Class.forName(activityToStart);
        Intent intent = new Intent(this, c);
        startActivity(intent);
    } catch (ClassNotFoundException e) {
        // print exception
    }

Put it in adapter when page is to be changed.

Ana
  • 166
  • 1
  • 16