How to get the position of cardView item in recyclerView?
Asked Answered
L

5

5

I created one adapter class for recycler for populating cardview layout in recyclerview. It is working fine, but when i click cardView item in recyclerview i need to get position of that cardview item , based on that i need to write a Intent activity. Along with how to delete that cardview item when i swipe left to right. MyAdapter class.

public class MyAdapter extends RecyclerView.Adapter<MyAdapter.ViewHolder> {
    private NavigationItem[] navigationItem;
    private Context mContext;

    public MyAdapter(NavigationItem[] navigationItem) {
        this.navigationItem = navigationItem;
    }

    @Override
    public MyAdapter.ViewHolder onCreateViewHolder(ViewGroup parent, int viewType) {
        View itemLayoutView = LayoutInflater.from(parent.getContext())
                .inflate(R.layout.navigation_row_cardview, null);
        ViewHolder viewHolder = new ViewHolder(itemLayoutView);
        return viewHolder;
    }

    @Override
    public void onBindViewHolder(MyAdapter.ViewHolder holder, int position) {
        holder.txtViewTitle.setText(navigationItem[position].getTitle());
    }

    @Override
    public int getItemCount() {
        return navigationItem.length;
    }

    public class ViewHolder extends RecyclerView.ViewHolder {
        @InjectView(R.id.hambergerRecyclerView)
        public RelativeLayout recyclerView;
        public TextView txtViewTitle;

        public ViewHolder(final View itemLayoutView) {
            super(itemLayoutView);
            ButterKnife.inject(this, itemLayoutView);
            txtViewTitle = (TextView) itemLayoutView.findViewById(R.id.navigationItemOptionName);

            itemLayoutView.setOnClickListener(new View.OnClickListener() {
                @Override
                public void onClick(View view) {
                    // int itemPosition = RecyclerView.getChildPosition(view);
                    int itemPosition = recyclerView.getChildAdapterPosition(view);
                    String item = navigationItem.get(itemPosition);
                    Toast.makeText(mContext, item, Toast.LENGTH_LONG).show();
                }
            });
        }
    }
}
Latricelatricia answered 9/9, 2015 at 7:46 Comment(0)
E
15

Short Answer

  1. Getting the position of CardView item

    when i click cardView item in recyclerview i need to get position of that cardview item

    use setTag() in the onBindViewHolder method of your adapter and getTag() in your OnClickListener implementation.

    you can also use getAdapterPosition() - see https://mcmap.net/q/276672/-recyclerview-get-position-and-switch-to-activity

    EDIT: as mentioned in the comments if you need to implement swipes, use the getAdapterPosition() method instead - this makes sure that the positions are not off.

  2. Launching an activity

    based on that i need to write a Intent activity

    create and start a new Intent in your OnClickListener implementation

    Intent newIntent = new Intent(this, YourNewActivity.class);    
    startActivity(newIntent);
    

Long Answer

How to get the position of a CardView item in the RecyclerView list?

when i click cardView item in recyclerview i need to get position of that cardview item

I used the setTag() and getTag() methods of View. You can also use getAdapterPosition - see https://mcmap.net/q/276672/-recyclerview-get-position-and-switch-to-activity

The View can be a TextView, ImageView, CardView, even a View (which could contain text views, image views and so forth) - basically ok if it inherits from the View Object.

  • first, look at the onCreateViewHolder method below. layoutInflater inflates the views in my XML layout file item_view.xml. Any views in that layout file will be accessible in the constructor.

    @Override
    public myViewHolder onCreateViewHolder(ViewGroup parentViewGroup, int i) {
        ...
    
        View itemView = layoutInflater.inflate(R.layout.item_view, parentViewGroup, false);
        return new myViewHolder(itemView);
    }
    
  • define a constant for your View object such as mView and set it to the View you wish to set the onClickListener to / get the position from.

    private class myViewHolder extends RecyclerView.ViewHolder {
        public View mView;
    
        public myViewHolder(View view) {
            super(view);
            mView = view;
        }
    }
    

    In the previous case, I set mView to the parent View.

    If you want to access a specific View from the item_view.xml layout file inflated in onCreateViewHolder -- define another constant, set it using view.findViewbyId() and do not forget to cast the View (see below).

    private class myViewHolder extends RecyclerView.ViewHolder {
        public CardView mCardView;
    
        public myViewHolder(View view) {
            super(view);
            mCardView = (CardView) view.findViewById(R.id.card_view);
        }
    }
    
  • use setTag() in the onBindViewHolder method of your adapter class. Each CardView now has its position in the RecyclerView list as a tag.

    @Override
    public void onBindViewHolder(myViewHolder viewHolder, int position) {
        viewHolder.mCardView.setTag(position);
    }
    
  • use getTag() to access the position of each CardView in your RecyclerView list: we have 2 ways for this (in Activity or in XML).

    set onClickListener in your ViewHolder constructor (do not forget to implement View.OnClickListener) and edit the onClick method

    private class myViewHolder extends RecyclerView.ViewHolder implements View.OnClickListener {
               public View mCardView;
    
               public myViewHolder(View view) {
                   super(view);
                   mCardView = (CardView) view.findViewById(R.id.card_view);
    
                   mCardView.setOnClickListener(this);
               }
           }
    
    @Override
    public void onClick(View view) {
        int position = (int) view.getTag();           
        Toast.makeText(view.getContext(),Integer.toString(position),Toast.LENGTH_SHORT).show();
    }
    

    OR set the onClick attribute in your XML layout for CardView android:onClick="positionAction"

    <android.support.v7.widget.CardView
        android:id="@+id/card_view"
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:onClick="positionAction">    
    
    </android.support.v7.widget.CardView>
    

    and create a method in the activity that contains the recycler view.

    public void positionAction(View view) {
        int position = (int) view.getTag();
        Toast.makeText(view.getContext(),Integer.toString(position),Toast.LENGTH_SHORT).show();
    }
    

For both options above, you can use String position = "Position " + view.getTag.toString(); instead of int position = (int) view.getTag; if you want to obtain the position as a String.

Note 1: You can only use getTag() on View objects whose setTag() method has been called (or else you will get a NullPointerException).

Note 2: I did not use a key for the setTag() and getTag() methods, which you could have done if you are setting several tags for each View.

How to start an activity based on the CardView clicked?

based on that i need to write a Intent activity

To start a new activity based on the CardView item the user clicks on, add the two lines below in the onClick method or in the positionAction method (based on the one you chose to use).

Intent newIntent = new Intent(this, YourNewActivity.class);    
startActivity(newIntent);

If you want to pass an object from one activity to the other, use

Intent newIntent = new Intent(this, YourNewActivity.class);
newIntent.putExtra("Item Object", itemList.get(position));
startActivity(newIntent);

and in the new activity (YourNewActivity class) :

itemReceived = new Item();
itemReceived = (Item) getIntent().getSerializableExtra("Item Object");

where itemList is an ArrayList of Item() objects.

References: StackOverflow | Tuts+

Eggshaped answered 9/10, 2015 at 0:16 Comment(2)
using setTag() and getTag() on RecyclerView with swipes will not work. Once you delete an item, all the positions recorded by setTag() are going to be off for all the items below the deleted position.Omland
@Omland you are right - I have edited my answer. thanks!Eggshaped
A
2

Implement onClick in onBindViewHolder, then you will get position.

Absolutism answered 9/9, 2015 at 7:50 Comment(1)
@Castorena you do not need to use getAdapterPosition(), you can use position from onBindViewHolder(ViewHolder holder, int position)Absolutism
T
2

Update your viewholder like this

public class ViewHolder extends RecyclerView.ViewHolder { 
    @InjectView(R.id.hambergerRecyclerView)
    public RelativeLayout recyclerView;
    public TextView txtViewTitle;
    public ViewHolder(final View itemLayoutView) {
        super(itemLayoutView);
        ButterKnife.inject(this, itemLayoutView);
        txtViewTitle = (TextView) itemLayoutView.findViewById(R.id.navigationItemOptionName);

        itemLayoutView.setOnClickListener(new View.OnClickListener() {
            @Override 
            public void onClick(View view) {
               //int itemPosition = RecyclerView.getChildPosition(view); 
                int itemPosition=getAdapterPosition();
                String item = navigationItem.get(itemPosition);
                Toast.makeText(mContext, item, Toast.LENGTH_LONG).show();
            } 
        }); 
    } 


} 
Tseng answered 9/9, 2015 at 8:9 Comment(3)
string item=navigationItem.get(itemPosition);==> here get() showing error... can u check this ...Latricelatricia
navigationItem.get(getAdapterPosition()); change something like thisCastorena
@androidstar still not getting position ?Tseng
S
1

You can try passing position to ViewHolder from onBindViewHolder

@Override   
public void onBindViewHolder(MyAdapter.ViewHolder holder, int position) {
    holder.txtViewTitle.setText(navigationItem[position].getTitle());
    //set position to holder
    holder.position = position; 
}


public class ViewHolder extends RecyclerView.ViewHolder {
        @InjectView(R.id.hambergerRecyclerView)
        public RelativeLayout recyclerView;
        public TextView txtViewTitle;
        //have a position field in view holder
        public int position;

        public ViewHolder(final View itemLayoutView) {
            super(itemLayoutView);
            ButterKnife.inject(this, itemLayoutView);
            txtViewTitle = (TextView) itemLayoutView.findViewById(R.id.navigationItemOptionName);

            itemLayoutView.setOnClickListener(new View.OnClickListener() {
                @Override
                public void onClick(View view) {
                    // int itemPosition = RecyclerView.getChildPosition(view);
                    int itemPosition = position;
                    String item = navigationItem.get(itemPosition);
                    Toast.makeText(mContext, item, Toast.LENGTH_LONG).show();
                }
            });
        }
}
Stymie answered 9/9, 2015 at 10:35 Comment(0)
D
0

Try this on your onBindViewHolder in adapter

myViewHolder1.itemView.setTag(new Integer(position));

and get like this on your OnClickListener:

Integer pos;
pos = (Integer) view.getTag();
Dissidence answered 8/12, 2017 at 13:19 Comment(0)

© 2022 - 2024 — McMap. All rights reserved.