How do I get the position selected in a RecyclerView?

前端 未结 13 2516
自闭症患者
自闭症患者 2020-11-27 04:40

I am experimenting with the support library\'s recyclerview and cards. I have a recyclerview of cards. Each card has an \'x\' icon at the top right corner to remove it:

13条回答
  •  夕颜
    夕颜 (楼主)
    2020-11-27 04:59

    Personally, the simplest way that I have found and works great for me is as follows:

    Create an interface inside your "RecycleAdapter" Class (Subclass)

    public interface ClickCallback {
        void onItemClick(int position);
    }
    

    Add a variable of the interface as a parameter in the Constructor.

    private String[] items;
    private ClickCallback callback;
    
    public RecyclerAdapter(String[] items, ClickCallback clickCallback) {
        this.items = items;
        this.callback = clickCallback;
    }
    

    Set a Click listener in the ViewHolder (another subclass) and pass the 'position' to through the interface

        AwesomeViewHolder(View itemView) {
            super(itemView);
            itemView.setOnClickListener(new View.OnClickListener() {
                @Override
                public void onClick(View v) {
                    callback.onItemClick(getAdapterPosition());
                }
            });
            mTextView = (TextView) itemView.findViewById(R.id.mTextView);
        }
    

    Now, when initializing the recycler adapter in an activity/fragment, just Create a new 'ClickCallback' (interface)

    String[] values = {"Hello","World"};
    RecyclerAdapter recyclerAdapter = new RecyclerAdapter(values, new RecyclerAdapter.ClickCallback() {
        @Override
        public void onItemClick(int position) {
             // Do anything with the item position
        }
    });
    

    That's it for me. :)

提交回复
热议问题