0

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 ...
Alex Rodionow
  • 247
  • 3
  • 13
  • 3
    [Call `smoothScrollToPosition()` on the `RecyclerView`](https://developer.android.com/reference/kotlin/androidx/recyclerview/widget/RecyclerView#smoothscrolltoposition). The top would be position `0`. – CommonsWare Apr 18 '21 at 16:48
  • thank you. But how can I call anything on recyclerView in the onOptionItemSelected()? – Alex Rodionow Apr 18 '21 at 16:52
  • 1
    Store your `RecyclerLayoutBinding` in a `lateinit var` property, so you can refer to `binding.recyclerView` in your `onOptionsItemSelected()` method. – CommonsWare Apr 18 '21 at 16:53
  • private lateinit var mBinding = RecyclerLayoutBinding.bind(// here I cannot write view) underscores "lateinit" word red with error "'lateinit' modifier is not allowed on properties with initializer" – Alex Rodionow Apr 18 '21 at 17:00
  • 1
    Yess, you see this error because lateinit modifier is used when you specify the value of a var at a later point in time. Using, private lateinit var mBinding = RecyclerLayoutBinding.bind(), you are doing exactly the opposite of what lateinit is used for. What you should do is, private lateinit var mBinding Then specify the value of mBinding later, inside your onViewCreated like this mBinding = RecyclerLayoutBinding.bind() – Priyansh Kedia Apr 18 '21 at 17:09
  • thanks all for help – Alex Rodionow Apr 18 '21 at 17:51

0 Answers0