Jonas Rotilli Jonas Rotilli - 14 days ago 7
Android Question

how to implement a SetOnItemClickListener FirebaseRecyclerViewAdapter

how to implement a SetOnItemClickListener event in a Firebase RecyclerView Adapter?
I use the example of documentation, chat app:

private FirebaseRecyclerViewAdapter mAdapter;

RecyclerView recycler = (RecyclerView) findViewById(;
recycler.setLayoutManager(new LinearLayoutManager(this));

mAdapter = new FirebaseRecyclerViewAdapter<ChatMessage, ChatMessageViewHolder>(ChatMessage.class, android.R.layout.two_line_list_item, ChatMessageViewHolder.class, mRef) {
public void populateViewHolder(ChatMessageViewHolder chatMessageViewHolder, ChatMessage chatMessage) {


There are probably many ways to do this, but this is the one I just quickly tried.

The ChatMessageViewHolder class has a member field where it keeps the root view for each chat message:

public static class ChatHolder extends RecyclerView.ViewHolder {
    View mView;

    public ChatHolder(View itemView) {
        mView = itemView;

We can use that mView member to get access to the clickable view. You should add a getter for mView, but I'm trying to minimize the changes here.

So then in populateView we can use the overload that has an additional position parameter and wire things up with an OnClickListener like this:

    mRecycleViewAdapter = new FirebaseRecyclerAdapter<Chat, ChatHolder>(Chat.class, R.layout.message, ChatHolder.class, mChatRef) {
        public void populateViewHolder(ChatHolder chatView, Chat chat, final int position) {

            if (mAuthData != null && chat.getUid().equals(mAuthData.getUid())) {
            } else {

            chatView.mView.setOnClickListener(new View.OnClickListener() {
                public void onClick(View view) {
                    Log.w(TAG, "You clicked on "+position);

The answers to this question offer tons of inspiration: RecyclerView onClick. As long as you can determine the position that the user clicked on, you can use the mRecycleViewAdapter.getRef(position) snippet to get the database reference of the item that was clicked.


On second thought I might like this answer better

    mMessages.addOnItemTouchListener(new RecyclerItemClickListener(this, new RecyclerItemClickListener.OnItemClickListener() {
        public void onItemClick(View view, int position) {
            Log.w(TAG, "You clicked on "+position);

It uses the RecyclerItemClickListener helper class from the answer I linked. And as already said: as long as you have a click/touch listener that tells you the position of the item that was selected, the rest FirebaseUI aspect of it will be the same: call adapter.getRef(position) to get a database reference for the selected item.