Recycler view inside NestedScrollView causes scroll to start in the middle Recycler view inside NestedScrollView causes scroll to start in the middle android android

Recycler view inside NestedScrollView causes scroll to start in the middle


I solved such issue by setting:

<ImageView ...android:focusableInTouchMode="true"/>

to my view above RecyclerView (which was hidden after unwanted scroll). Try to set this property to your LinearLayout above RecyclerView or to LinearLayout which is container of RecyclerView (helped me in another case).

As I see in NestedScrollView source it tries to focus the first possible child in onRequestFocusInDescendants and if only RecyclerView is focusable it wins.

Edit (thanks to Waran): and for smooth scroll don't forget to set yourRecyclerView.setNestedScrollingEnabled(false);


In your LinearLayout immediate after NestedScrollView, use android:descendantFocusability in the following way

<LinearLayout        android:layout_width="match_parent"        android:layout_height="match_parent"        android:orientation="vertical"        android:padding="10dp"        android:descendantFocusability="blocksDescendants">

EDIT

Since many of them getting this answer useful, will also provide explanation.

The use of descendantFocusability is given here. And as of focusableInTouchMode over here.So using blocksDescendants in descendantFocusability do not allows it's child to gain focus while touching and hence unplanned behaviour can be stopped.

As for focusInTouchMode, both AbsListView and RecyclerView calls the method setFocusableInTouchMode(true); in their constructor by default, so it is not required to use that attribute in your XML layouts.

And for NestedScrollView following method is used:

private void initScrollView() {        mScroller = ScrollerCompat.create(getContext(), null);        setFocusable(true);        setDescendantFocusability(FOCUS_AFTER_DESCENDANTS);        setWillNotDraw(false);        final ViewConfiguration configuration = ViewConfiguration.get(getContext());        mTouchSlop = configuration.getScaledTouchSlop();        mMinimumVelocity = configuration.getScaledMinimumFlingVelocity();        mMaximumVelocity = configuration.getScaledMaximumFlingVelocity();    }

Here, setFocusable() method is used instead of setFocusableInTouchMode(). But according to this post, focusableInTouchMode should be avoided unless for certain conditions as it breaks consistency with Android normal behaviour. A game is a good example of an application that can make good use of the focusable in touch mode property. MapView, if used in fullscreen as in Google Maps, is another good example of where you can use focusable in touch mode correctly.


android:descendantFocusability="blocksDescendants"

inside LinearLayout Worked for me .