How to pass or send data from recyclerview adapter to fragment

前端 未结 5 1376
执念已碎
执念已碎 2021-01-16 12:20

How to pass data from recyclerview adapter to fragment and what i have to write the code in fragment to receive data.I have already check the links in this website but unfor

5条回答
  •  爱一瞬间的悲伤
    2021-01-16 12:45

    You can pass data by attaching a callback into your adapter:

    Create an interface:

    interface OnTextClickListener {
        void onTextClick(ExampleItem data);
    }
    

    Delegate the callback:

    class ExampleAdapter extends RecyclerView.Adapter {
    
        List items;
        OnTextClickListener listener;
    
        ExampleAdapter(List items, OnTextClickListener listener) {
            this.items = items;
            this.listener = listener;
        }
    
        @Override
        public void onBindViewHolder(ExampleViewHolder viewHolder, int position) {
            viewHolder.textView.setOnClickListener(new View.OnClickListener() {
                @Override
                public void onClick(View v) {
                    // Say you want to pass an ExampleItem back to the fragment...
                    ExampleItem data = items.get(position);
                    listener.onTextClick(data);
                }
            });
        }
    }
    

    Implement the fragment with the interface:

    class YourFragment extends Fragment implements OnTextClickListener {
    
        public onViewCreated(View view, Bundle savedInstanceState) {
            super.onViewCreated(view, savedInstanceState);
            recyclerView.setAdapter(new ExampleAdapter(this));
        }
    
        void onTextClick(ExampleItem data) {
            // Now you can do however you want with the data here...
            Toast.makeText(getActivity(), "Got: " + data, Toast.LENGTH_SHORT).show()
        }
    }
    

提交回复
热议问题