0

I used recyclerview inside viewpager. Now I want to change the view of my fragment when I scroll the recycler view. I am using mvvm and liveData and I want to use viewModel and send the scroll data to my viewModel and in view I observe the viewModel data that comes from viewPager adapter. How can I send the data from viewPager adapter and use them in its fragment?

val linearLayoutManager =
        LinearLayoutManager(container.context, LinearLayoutManager.VERTICAL, false)
    recCafeList = binding.recCafeList

    recCafeList.layoutManager = linearLayoutManager
    recCafeList.adapter = mAdapter



    recCafeList.setOnScrollListener(object : RecyclerView.OnScrollListener() {

        override fun onScrolled(recyclerView: RecyclerView, dx: Int, dy: Int) {
            super.onScrolled(recyclerView, dx, dy)

            val po = linearLayoutManager.findFirstVisibleItemPosition()
            val po2 = linearLayoutManager.findFirstCompletelyVisibleItemPosition()
            
            // I want to send @po and @po2 to viewModel and use them in fragment
            
            Log.i("scrollListener", "$po //// $po2")
        }

    })

    container.addView(binding.root)

    return binding.root

1 Answers1

0

You can use custom Listener. Create it inside the fragment and transfer it to pagers adapter. And in any time you can call listeners method. Like that - Android communication between fragment and baseadapter

It is easy and nice practice solution.

Yegorf
  • 400
  • 2
  • 11
  • The question is about ViewPager, not ListView. – EpicPandaForce Apr 03 '21 at 19:15
  • Its no difference at all, bro. Solution is absolutely the same for ListView, RecyclerView, ViewPager, and any other view, that uses an adapter. – Yegorf Apr 03 '21 at 19:27
  • No, FragmentPagerAdapter behaves differently, therefore the solution is a bit different. – EpicPandaForce Apr 03 '21 at 19:31
  • Argue, whats the difference? Youe creating the listener in the fragment, provide it in Adapter, in adapter in the any place you calling the listeners method. – Yegorf Apr 03 '21 at 19:33
  • "Provide it in the adapter"? That will not work after process death. – EpicPandaForce Apr 03 '21 at 20:00
  • What are you talking about? Listener will work while fregment is alive! – Yegorf Apr 03 '21 at 20:43
  • Let us [continue this discussion in chat](https://chat.stackoverflow.com/rooms/230711/discussion-between-yegorf-and-epicpandaforce). – Yegorf Apr 03 '21 at 21:34
  • `FragmentPagerAdapter.getItem()` is used to create the Fragment if it is not yet added. Once it is added, the FragmentManager will recreate it, and it will have nothing to do do with the FragmentPagerAdapter. – EpicPandaForce Apr 04 '21 at 12:06