Reputation: 1127
I've got a CoordinatorLayout, and I need to programmatically scroll vertically to have a specific view anchored to the top as a sticky view. The stickiness works by having an AppBarLayout with app:layout_scrollFlags="scroll|snap"
set on the view I want to make sticky. The programmatically scrolling of the CoordinatorLayout is proving to be problematic.
The structure of the CoordinatorLayout content is:
<com.google.android.material.appbar.AppBarLayout
…
</com.google.android.material.appbar.AppBarLayout>
<!--list of reviews-->
<RecyclerView
../>
<androidx.constraintlayout.widget.ConstraintLayout
..
</androidx.constraintlayout.widget.ConstraintLayout>
<com.google.android.material.floatingactionbutton.FloatingActionButton
.. />
I've tried scrollTo
, scrollBy
but can't seem to calculate the correct value for Y. I thought height - view.top would do it but it didn't.
I've tried wrapping in a ScrollView but this caused a RecyclerView in the same layout to disappear, and the smoothScroll didn't work anyway.
I've tried
val view = mLayout.findViewById<ConstraintLayout>(R.id.view)
val rect = Rect(0, 0, view.getWidth(), view.getHeight())
view.requestRectangleOnScreen(rect, true) // and tried false
I've tried view.parent.requestChildFocus(view, view)
--
I'm now trying a new approach, I'm trying to set the views above the one I need to scroll to to View.GONE - which works, except that setting the views above as GONE causes the anchored view to lose its 'stickiness'. I tried adding this view above it but still once I set the above views to GONE
the stickiness won't work.
<View
android:id="@+id/sticky_helper"
android:layout_width="wrap_content"
android:layout_height="1dp"
app:layout_scrollFlags="scroll|snap"/>
However when I just set the views to INVISIBLE
the stickiness still works so it seems to be to do with setting them to GONE even though the above view is still visible.
If anyone has a workaround for the stickiness, or indeed knows how to scroll to specific view in CoordinatorLayout I'd be very grateful.
Upvotes: 0
Views: 1627
Reputation: 1402
Hope, this will help you:
scroll your RecyclerView
to 0 position:
recyclerView.smoothScrollToPosition(0)
Expand your AppBarLayout
:
app_bar.setExpanded(true, true)
And bacause of I don't know what is inside your AppBarLayout
can't say how to scroll it in right way :) But your AppBarLayout
will be expanded and all of it's views will be shown
Upvotes: 2