Jawegiel
Jawegiel

Reputation: 101

Android recyclerview requestFocus when scrolling up and down for edittext items only

I have recyclerview consisting of edittexts only. Those edittexts have various length. I want to stop scrolling my recyclerview on onViewAttachedToWindow when holder.getAdapterPosition() == vhIndex.

The problem is when edittext selection is either:

  1. 0 and scrolling is towards down,
  2. last character and scrolling is towards up

then recyclerview is not stopping to focus on this edittext or stopping ungracefully (both of them seem to act randomly).

Here is my code:

@Override
public void onBindViewHolder(ViewHolder holder, int position) {
    MyEditText myEt = (MyEditText) holder.itemView;
    (...)
    myEt.setOnFocusChangeListener(this::doOnFocus);
    (...)
}

private void doOnFocus(View view, boolean hasFocus) {
    if (hasFocus) {
        vHIndex = bigText.getChildAdapterPosition(view);
        selections.put(vHIndex, ((MyEditText) view).getSelectionStart());
    }
}

@Override
public void onViewAttachedToWindow(@NonNull ViewHolder holder) {
    super.onViewAttachedToWindow(holder);
    setSelection(holder);
}

private void setSelection(ViewHolder holder) {
    if (holder.getAdapterPosition() == vHIndex && selections.get(vHIndex) != null) {
        if (selections.get(vHIndex) > 0) {
            setSelection(holder, selections.get(vHIndex));
        }
    }
}

@Override
protected void onSelectionChanged(int selStart, int selEnd) {
    super.onSelectionChanged(selStart, selEnd);
    if (!isJustPasted && (!isScrolling || selStart > 0)) {
        selections.put(vHIndex, selStart);
    }
}

Upvotes: 0

Views: 33

Answers (0)

Related Questions