Implementing RecyclerView Click Listener

Implementing item click listener on RecyclerView using Interface method.

Interface

public interface CustomItemClickListener {  
    void onItemClick(View v, int position);
    void onActionClick(View v, int position);
}

Fragment

ObjectAdapter objectAdapter = new ObjectAdapter(itemsList, new CustomItemClickListener() {  
    @Override
    public void onItemClick(View v, int position) {
        Toast.makeText(getActivity(), "Card Clicked: " + position, Toast.LENGTH_SHORT).show();

    }
    @Override
    public void onActionClick(View v, int position) {
        Toast.makeText(getActivity(), "Action Clicked: " + position, Toast.LENGTH_SHORT).show();
    }
});

Adapter

private CustomItemClickListener clickListener;

public AllListsAdapter(ArrayList<Object> objectList, CustomItemClickListener clickListener) {  
    this.objectList = objectList;
    this.clickListener = clickListener;
}

@Override
public ObjectAdapter.ViewHolder onCreateViewHolder(ViewGroup v, int viewType) {

    View itemView = LayoutInflater.from(v.getContext()).inflate(R.layout.items_all_lists, v, false);

    final ObjectAdapter.ViewHolder oa = new ObjectAdapter.ViewHolder(itemView);
    itemView.setOnClickListener(new View.OnClickListener() {
        @Override
        public void onClick(View v) {
            clickListener.onItemClick(v, oa.getAdapterPosition());
        }
    });

    return oa;
}

@Override
public void onBindViewHolder(ObjectAdapter.ViewHolder viewHolder, final int i) {

    Object o = object.get(i);
    viewHolder.iv_action.setOnClickListener(new View.OnClickListener() {
        @Override
        public void onClick(View v) {
            clickListener.onActionClick(v, i);
        }
    });
}

Aiman Baharum

More about this blog https://github.com/aimanbaharum/random-wiki/wiki

Kuala Lumpur, Malaysia http://www.aimanbaharum.com

Subscribe to Knowledge Log

Get the latest posts delivered right to your inbox.

or subscribe via RSS with Feedly!