cachapa / ExpandableLayout

An expandable layout container for Android
Apache License 2.0
2.34k stars 273 forks source link

Scroll RecyclerView to show selected item expand on top #84

Closed androiddevcoding closed 4 years ago

androiddevcoding commented 4 years ago

The task is as follows: after expanding the element, scroll to the desired position. RecyclerView contains a child of the RecyclerView.

item_parent_recycler.xml

.....
            <net.cachapa.expandablelayout.ExpandableLayout
                android:id="@+id/expandable_layout"
                android:layout_width="match_parent"
                android:layout_height="wrap_content"
                app:el_duration="300"
                app:el_expanded="false"
                app:layout_constraintBottom_toBottomOf="parent"
                app:layout_constraintTop_toBottomOf="@+id/textView">>

                <androidx.recyclerview.widget.RecyclerView
                    android:id="@+id/rv_child"
                    android:layout_width="match_parent"
                    android:layout_height="match_parent"
                    android:layout_alignParentTop="true"
                    android:layout_centerHorizontal="true"
                    android:orientation="horizontal"
                    tools:layout_editor_absoluteX="74dp" />
            </net.cachapa.expandablelayout.ExpandableLayout>

Решение: onBindViewHolder:

   val clickPos: (pos: Int) -> Unit
   ....
   holder.itemView.setOnClickListener {
            if (holder.coll.isExpanded) {
                holder.coll.collapse()
                holder.imageView.setImageResource(R.drawable.ic_arrow_bottom)
            } else {
                holder.coll.expand()
                holder.coll.setOnExpansionUpdateListener { expansionFraction, state ->
                    if (expansionFraction == 1F)
                        clickPos.invoke(
                            position
                        )
                }
                holder.imageView.setImageResource(R.drawable.ic_arrow_top)
            }
        }

fragment:

private fun initRecycler() {
        adapter = ParentListAdapter(activity!!, { domophoneId, doorId ->
            mViewModel.openDoor(domophoneId, doorId)
        }, { position ->
            val layoutManager = recyclerView
                .layoutManager as LinearLayoutManager
            val smoothScroller: SmoothScroller = object : LinearSmoothScroller(context) {
                override fun getVerticalSnapPreference(): Int {
                    return SNAP_TO_START
                }
            }
            smoothScroller.targetPosition = position
            layoutManager.startSmoothScroll(smoothScroller)
        })

Maybe someone will be useful. Thanks.

cachapa commented 4 years ago

Not an issue