HEATH3N HEATH3N - 5 months ago 14
Android Question

Accessing a list item's view and data at the same time

I am working on a messaging application and would like to set the chat bubble as coming from the left or the right depending on who the owner of the message is.

public class Message {
public String messageText;
public boolean mine;

// ...Constructor
}


Inside
MessageAdapter
I have:

@Override
public MessageHolder onCreateViewHolder(ViewGroup parent, int viewType) {

View view = LayoutInflater.from(parent.getContext()).inflate(this.itemResource, parent, false);
return new MessageHolder(this.context, view);
}

@Override
public void onBindViewHolder(MessageHolder holder, int position) {

Message message = this.messages.get(position);
holder.bindMessage(message);
}


I have been following tutorials to migrate from ListView to RecyclerView and am now unclear as to how to access both an item's data and its view at the same time without getting
NullPointerException
. The code I want to use looks like this:

Drawable background = getResources().getDrawable(message.mine ? R.drawable.bubble_right : R.drawable.bubble_left);
background.setColorFilter(getResources().getColor(R.color.ColorPrimary), PorterDuff.Mode.SRC_IN);

view.findViewById(R.id.message_text).setBackgroundDrawable(background);


However, if I put it in
onCreateViewHolder
I can't figure out how to access the individual message to check ownership. If I put it in
onBindViewHolder
I have
message
but can't get its view. How do I solve this?

Neo Neo
Answer

If you are moving from ListView to RecyclerView, then it's very easy to understand.

getView() (of ListView) == onCreateViewHolder() + onBindViewHolder();

If you remember we need to check view given by getView is null or not, and if it's null then we need to take care of instancing otherwise set the data to corresponding views. RecyclerView are making our life easy, the onCreateView creates new instance of the view of each row(minimum required) and onBindViewHolder takes care of binding data to each view element.

I think now you are clear why and how to handle these two methods of RecyclerView. As per your code, the line view.findViewById(R.id.message_text) should be moved to your ViewHolder class. And the following lines will go in onBindViewHolder

Drawable background = getResources().getDrawable(message.mine ? R.drawable.bubble_right : R.drawable.bubble_left);
background.setColorFilter(getResources().getColor(R.color.ColorPrimary), PorterDuff.Mode.SRC_IN);
holder.your_view.setBackgroundDrawable(background);

Let me know if you want to know further clarifications.

Comments