RecyclerView : get position and switch to activity

后端 未结 3 602
刺人心
刺人心 2020-12-13 16:18

How is it possible to get the position of the item which was clicked in the RecyclerView row and than make a intent to an activity in the onClick m

相关标签:
3条回答
  • 2020-12-13 16:25

    or you can just add :

    public class MyAdapter extends RecyclerView.Adapter<MyAdapter.MyViewHolder > {
    
    ...
        class MyViewHolder extends RecyclerView.ViewHolder {
    
            public MyViewHolder (View itemView) {
                super(itemView);
    
                itemView.setOnClickListener(new View.OnClickListener() {
                    @Override
                    public void onClick(View v) {
                        Log.d(TAG, "Element " + getAdapterPosition() + " clicked.");
                    }
                });
            }
    
    
        }
    
    0 讨论(0)
  • 2020-12-13 16:39

    Within your onClick(View v) you can simply call getLayoutPosition() which will return the position where the click happened. Check the official docs for further information.

    So your code would be something like this:

    @Override
    public void onClick(View v) {
        switch(getLayoutPosition()){
           //TODO
        }
    }
    

    Preferably you should use an Interface to handle the click.

    0 讨论(0)
  • 2020-12-13 16:49

    You can get postion from ViewHolder by using getAdapterPosition() method. Like in code below:

    public class SergejAdapter extends RecyclerView.Adapter<SergejAdapter.MyViewHolder>{
    
        ...
    
        class MyViewHolder extends RecyclerView.ViewHolder implements View.OnClickListener{
    
    
            @Override
            public void onClick(View v) {
                // here you use position
                int position = getAdapterPosition();
                ...
    
            }
        }
    }
    
    0 讨论(0)
提交回复
热议问题