I have a Scrollview which contains an ImageView and RecyclerView. if navigation drawer opened then closed the RecyclerView auto scrolling to top, How to stop this?
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="match_parent"
android:layout_height="match_parent"
xmlns:app="http://schemas.android.com/apk/res-auto">
<ScrollView
android:layout_width="match_parent"
android:layout_height="match_parent"
android:id="@+id/scrollViewMain"
>
<LinearLayout
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:orientation="vertical">
<ImageView
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:id="@+id/imageView_main_icons_line"
android:src="@drawable/main_line" />
...
<android.support.v7.widget.RecyclerView
android:id="@+id/recyclerView_activity_main_passenger_log"
android:paddingBottom="2dp"
android:layout_width="match_parent"
android:layout_height="wrap_content" />
</LinearLayout>
</ScrollView>
</RelativeLayout>
This problem because of recyclerView has default focus.
Solution
<LinearLayout
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:descendantFocusability="blocksDescendants"
android:orientation="vertical">
Add android:descendantFocusability="blocksDescendants"
to your immediate layout of scrollView
That is because RecyclerView ALWAYS set:
setFocusableInTouchMode(true);
this is hard coded in its constructor.
so if you apply those attribute in your XML for a RecyclerView
android:focusable="false"
android:focudeableInTouchMode="false"
that would be useless, you end up with recycleView.isFocusable() == true...
so the most elegant solution is to disable foucusable for RecyclerView's Parent.
<LinearLayout
android:focusable="false"
android:focusableInTouchMode="false"
android:descendantFocusability="blocksDescendants"
...
>
<android.support.v7.widget.RecyclerView
...
/>
/>
or you can just simply setFocusable(false)
Check out clearFocus() from here Android Dev Doc.
You can set a DrawerListener to your navigation drawer and use the onDrawerStateChanged() or some of the other options from here to call clearFocus() on your RecyclerView.
Adding android:descendantFocusability="blocksDescendants"
can restrict scroll to recylerview but if you have edittext inside your layout, this property can block the focus of that particular edittext too. So if you are using this property please make sure you are removing this property in your kotlin/java class once the layout loaded.
parentLayout?.descendantFocusability = FOCUS_BEFORE_DESCENDANTS
(view as ViewGroup).descendantFocusability = FOCUS_BEFORE_DESCENDANTS
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With