Search code examples
androidandroid-fragmentsandroid-viewpager

Parent Fragment communication with fragment inside viewpager


  • I have one MainActivity with -> FragmentA which contains -> ViewPager with (Fragment1,Fragment2,Fragment3)
  • Now in FragmentA I have one spinner and any selection must reflect the changes inside viewpager's currently visible fragment.
  • How can I achieve that? I don't want to follow ViewModel or EventBus approach for now as I am working on very old project. I want to use interface to communicate between them.

Solution

  • Create an interface inside your FragmentA

    interface OnSpinnerValue{
        fun onSpinnerValueChanged()
    }
    

    Create a WeakReference for the current selected fragment

    private var _currentPage: WeakReference<OnSpinnerValue>? = null
    private val currentPage
        get() = _currentPage?.get()
    
    fun setCurrentPage(page: OnSpinnerValue) {
        _currentPage = WeakReference(page)
    }
    

    Now implement this interface in every child fragment of ViewPager

    class Fragment1() : Fragment(), OnAddEvent {
        override fun onSpinnerValueChanged() {
             // implement your method
        }
    }
    

    And, update currentPage value of the FragmentA, according to the selected fragment, and update it in onResume() of each child fragment

    override fun onResume() {
        super.onResume()
        (parentFragment as FragmentA).setCurrentPage(this)
    }
    

    Now, trigger onSpinnerValueChanged from your spinner's onItemSelected methods

    override fun onItemSelected(parent: AdapterView<*>?, view: View?, position: Int, id: Long) {
         currentPage?.onSpinnerValueChanged()
    }