How to make a recyclerView scroll to the top position by clicking menu item?

161 Views Asked by At

I need so that if one clicks the menu item "turn All Words On" (look below), then the view scrolls to the top position. How to do this from the onOptionItemSelected() method and what to type there?

Appreciate any help.

@AndroidEntryPoint
class VocabularyFragment : Fragment(R.layout.recycler_layout),
    VocabularyAdapter.OnVocItemClickListener {

    private val viewModel: VocabularyViewModel by viewModels()
    private lateinit var searchView: SearchView

    override fun onViewCreated(view: View, savedInstanceState: Bundle?) {
        super.onViewCreated(view, savedInstanceState)

        val binding = RecyclerLayoutBinding.bind(view)
        val vocabularyAdapter = VocabularyAdapter(this)
        binding.apply {
            recyclerView.apply {
                adapter = vocabularyAdapter
                layoutManager = LinearLayoutManager(requireContext())
                setHasFixedSize(true)
                itemAnimator = null // ХЗ НАДО ЛИ
            }
        }

        viewModel.words.observe(viewLifecycleOwner) {
            vocabularyAdapter.submitList(it)
        }

        setHasOptionsMenu(true)
    }

    override fun onOptionsItemSelected(item: MenuItem): Boolean {
        return when (item.itemId) {
            R.id.action_choose_all_categories -> {
                viewModel.onChooseCategoryClick(0)
                // HERE I NEED TO call the recycler view and make it scroll to the top to the 1st position
                true
            }
            //other items ...
0

There are 0 best solutions below