How to implement different clicks for each item in RecyclerView?

0

I'm developing an app, and it has recyclerView in conjunction with CardView . And all information is stored inside the app itself to be displayed in recyclerView . A part of the structure is this:

Album a = new Album("True Romance", 13, covers[0]);
        albumList.add(a);

        a = new Album("Xscpae", 8, covers[1]);
        albumList.add(a);

        a = new Album("Maroon 5", 11, covers[2]);
        albumList.add(a);

        a = new Album("Born to Die", 12, covers[3]);
        albumList.add(a);

        a = new Album("Honeymoon", 14, covers[4]);
        albumList.add(a);

        a = new Album("I Need a Doctor", 1, covers[5]);
        albumList.add(a);

        a = new Album("Loud", 11, covers[6]);
        albumList.add(a);

        a = new Album("Legend", 14, covers[7]);
        albumList.add(a);

        a = new Album("Hello", 11, covers[8]);
        albumList.add(a);

        a = new Album("Greatest Hits", 17, covers[9]);
        albumList.add(a);

        adapter.notifyDataSetChanged();
    }

And onClick comes right after:

recyclerView.addOnItemTouchListener(  
    new RecyclerItemClickListener(context, new RecyclerItemClickListener.OnItemClickListener() {
      @Override public void onItemClick(View view, int position) {
        // TODO Handle item click
      }
    })
); 

How do I adapt each item with a different click? For example:

  

Clicked on "True Romance" go to a new activity, "Xscpae" go to another activity ...

What is the logic? Can I do this?

    
asked by anonymous 10.02.2017 / 00:53

1 answer

1

One option is to have access to the clicked object, given its position in the onItemClick method.

You can create a method for this on the adapter that is associated with your RecyclerView, for example assuming that on your adapter you saved the list of albums in a variable called albumList :

public Album getItem(int position) {
  return albumList.get(position);
}

Then in your onItemClick method, just recover and implement the action in the best way for each album:

recyclerView.addOnItemTouchListener(  
    new RecyclerItemClickListener(context, new RecyclerItemClickListener.OnItemClickListener() {
      @Override public void onItemClick(View view, int position) {
        Album selectedAlbum = adapter.getItem(position);
        // Faca algo com o album
      }
    })
);
    
12.02.2017 / 00:35