How to set focus on the last element of an ArrayList<> in kotlin (Android)?

533 Views Asked by At

I'm new at kotlin and I would like some help in how to set focus of the scroll on the last element of an ArrayList<tags> here a look of my code

  <androidx.recyclerview.widget.RecyclerView
    android:id="@+id/RVTags"
    android:layout_width="match_parent"
    android:layout_height="0dp"
    android:layout_marginBottom="12dp"
    android:visibility="gone"
    app:layout_constraintBottom_toTopOf="@id/startStop"
    app:layout_constraintTop_toBottomOf="@id/ui_power_range_inventory_layout"
    />
class FindTagsAdapter internal constructor(
    private val ServicesList: ArrayList<Tag>
) :
    RecyclerView.Adapter<FindTagViewHolder>() {

    override fun onCreateViewHolder(parent: ViewGroup, viewType: Int): FindTagViewHolder {
        return FindTagViewHolder(LayoutInflater.from(parent.context), parent)
    }

    override fun onBindViewHolder(holder: FindTagViewHolder, position: Int) {
        holder.bind(ServicesList[position])
    }

    override fun getItemCount(): Int {
        return ServicesList.size
    }
}
2

There are 2 best solutions below

0
On BEST ANSWER

Solve my problem:

RecyclerView.scrollToPosition(var.lastIndex)

That way it scroll automatically to bottom.

0
On

You can scroll to the last item of your list with the smoothScrollToPosition() function.

You can create a function in your class for that action.

In my code, I assume that you use two global variables for storing your RecyclerView reference and your list of items and that you have already initialized your RecyclerView.

private var recyclerView: RecyclerView? = null
private var servicesList = arrayListOf<Tag>()

...

private fun focusLastItem() 
{
    if (servicesList.isNotEmpty()) {
        recyclerView?.smoothScrollToPosition(serviceList.size - 1)
    }
}

Then you can just call the focusLastItem function every time your list is updated.