androidandroid-fragmentsandroid-scrollviewandroid-architecture-navigationandroid-viewpager2

Can i obseve fragment scrolling in activity?


I structured it like this:

  1. FragmentContainerView in Main activity
  2. ViewPager2 in HomeFragment
  3. Nested scroll view / recycler view in ViewPager2 fragments

I want to set the visibility for a button in the main activity when the sub fragment in ViewPager is scrolled.

like if i scroll up the child fragment, i will see the main activity's button.

My sample code :

Main Activity

    <androidx.fragment.app.FragmentContainerView android:id="@+id/nav_host_fragment"/>
    
    <com.google.android.material.bottomnavigation.BottomNavigationView/>

    <com.google.android.material.floatingactionbutton.FloatingActionButton/>

HomeFragment

<androidx.constraintlayout.widget.ConstraintLayout>

        <com.google.android.material.tabs.TabLayout
            android:id="@+id/tab_layout"/>

        <androidx.viewpager2.widget.ViewPager2
            android:id="@+id/viewpager"
            android:layout_width="0dp"
            android:layout_height="0dp"/>

</androidx.constraintlayout.widget.ConstraintLayout>

One of child Fragment in ViewPager2

<androidx.core.widget.NestedScrollView
        android:id="@+id/scrollView"
        android:layout_width="match_parent"
        android:layout_height="match_parent"
        android:fillViewport="true"
        tools:context=".ui.PickupFragment">

        <LinearLayout
            android:layout_width="match_parent"
            android:layout_height="match_parent"
            android:orientation="vertical">
        ...
        </LinearLayout>

</androidx.core.widget.NestedScrollView>

please help for me.


Solution

  • You can achieve this by using a scroll listener on the NestedScrollView in the child fragment and communicating with the parent HomeFragment to update the visibility of the button in the main activity.

    Here's an example implementation:

    scrollView.setOnScrollChangeListener(NestedScrollView.OnScrollChangeListener { _, _, scrollY, _, _ ->
        // Notify HomeFragment when the scroll position changes
        (parentFragment as? HomeFragment)?.onChildScroll(scrollY)
    })
    
    
    fun onChildScroll(scrollY: Int) {
        // Update the visibility of the FloatingActionButton in the parent activity
        val fab = requireActivity().findViewById<FloatingActionButton>(R.id.fab)
        if (scrollY > 0) {
            fab.visibility = View.VISIBLE
        } else {
            fab.visibility = View.GONE
        }
    }
    

    Call onChildScroll from the child fragment's setOnScrollChangeListener whenever the scroll position changes. The parentFragment property is used to get a reference to the parent HomeFragment. This should update the visibility of the FloatingActionButton in the main activity whenever the child fragment is scrolled.