6

I'm trying to count the number of lines of a TextView in a RecyclerView adapter.

Following answers from other questions (although not related to RecyclerViews), I tried adding this to my onBindViewHolder method:

@Override
public void onBindViewHolder(final ViewHolder holder, int position) {
    Message message = messages.get(position);

    holder.textView.setText(message.getMessage());

    holder.textView.setVisibility(View.VISIBLE);

    // Get the number of lines
    holder.textView.post(new Runnable() {
        @Override
        public void run() {
            int lineCount = holder.textView.getLineCount();

            Log.d("COUNT", String.valueOf(lineCount));
        }
    });
}

But when I open my app, the first RecyclerView item will initially show COUNT 0 (even though it has 5 lines). But when I scroll down a few items and then scroll back up to the first item, it will show the correct number of lines (COUNT 5).

So what am I doing wrong?

Community
  • 1
  • 1

1 Answers1

2

textView is reference to converted view in layout manager. When run() is executed, holder.textView maybe used in another item.

UPDATED

If you fast scroll, some views maybe won't be prepared. You can check that text in current view equals message.

Message message = messages.get(position);

holder.textView.setText(message.getMessage());

holder.textView.setVisibility(View.VISIBLE);

// Get the number of lines
holder.textView.post(new Runnable() {
    @Override
    public void run() {
        if (holder.textView.getText().toString().equals(message.getMessage()) {
            int lineCount = holder.textView.getLineCount();
            Log.d("COUNT", String.valueOf(lineCount));
        }
    }
});