简体   繁体   中英

How to get the position of cardView item in recyclerView?

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();
                }
            });
        }
    }
}

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://stackoverflow.com/a/27886776/4658957

    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://stackoverflow.com/a/27886776/4658957

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+

onBindViewHolder实现onClick ,然后你将获得位置。

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();
            } 
        }); 
    } 


} 

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();
                }
            });
        }
}

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();

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM