Skip to content Skip to sidebar Skip to footer

How To Create A Interface In Main Activity And Pass The Data From Adapter To Main Activity Through The Interface?

I have created a RecyclerView in my fragment one and I have created a RecyclerViewAdapter to bind my date set to views that are displayed within the RecyclerView in my fragment one

Solution 1:

Step 1. Create Interface

public interface RecyclerViewItemInterface {

    void onItemClick(int position, String path);

}

Step 2. write set method in Adapter

private RecyclerViewItemInterface viewItemInterface;

 public void setViewItemInterface(RecyclerViewItemInterface viewItemInterface) {
        this.viewItemInterface = viewItemInterface;
    }

Step 3. Pass data & call Method like this

holder.itemView.setOnClickListener(new View.OnClickListener() {
                @Override
                public void onClick(View v) {

                    if (viewItemInterface != null) {
                        viewItemInterface.onItemClick(holder.getAdapterPosition(),"");
                    }
                }
            });

Step 4. Implement interface like this

bgImageAdapterNEW.setViewItemInterface(new RecyclerViewItemInterface() {

            @Override
            public void onItemClick(int position, String path) {

            }
        });

Solution 2:

as you talk above : In MyAdapter you can add

public interface onItemClickListener {
    public void onItemCLickListener(int position);
}

In onBindViewHolder you set listener on click with specific view you want:

holder.viewYouWant.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                if (onItemClickListener != null)
                    onItemClickListener.onItemCLickListener(position,data);
            }
 });

In MainActivity implements OnItemClickListener then wrap data in bundles and send it to fragment you can following here : Click listener for RecyclerView adapter


Post a Comment for "How To Create A Interface In Main Activity And Pass The Data From Adapter To Main Activity Through The Interface?"