How to pass or send data from recyclerview adapter to fragment

前端 未结 5 1372
执念已碎
执念已碎 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:43

    Have a IDataCollector interface. Implement her in the Fragment, pass the Fragment reference as a constructor parameter, and use it inside the adapter

    public interface IDataCollector {
        void setText(String text);
        void setAnything(Object anything);
    }
    
    // Fragment
    
    public class Fragment implements IDataCollector {
    
        private void initView() {
            // Add this as a parameter
            ExampleAdapter adapter = new ExampleAdapter(... , this);
        }
    
        @Override
        public void setText(String text){
            this.textField = text;
        }
    
        @Override
        public void setText(Object anything){
            this.anything = anything;
        }
    }
    
    // Adapter code
    
    // Constructor, parameters ommited
    public ExampleAdapter(...., IDataCollector dataCollector) {
        this.dataCollector = dataCollector;
    }
    
    @Override
    public void onBindViewHolder(@NonNull ExampleViewHolder exampleViewHolder, int i) {
        final ExampleItem currentItem=mExampleList.get(i);
        exampleViewHolder.mTextView.setText(currentItem.getmText());
        exampleViewHolder.mTextView.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                dataCollector.setText(((TextView)v.findViewById(R.id.label1)).getText());
                ....
            }
        });
    }
    

提交回复
热议问题