Home > Software engineering >  Fragment communication with fragment inside viewpager
Fragment communication with fragment inside viewpager

Time:10-27

  • 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.

CodePudding user response:

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()
}

CodePudding user response:

It is strange if you don't want to use ViewModel , I know may be it is not best solutions but you can :

  1. you can create function itIsYourFunctionToUpdate() inside your fragment and update him on FragmentA() , calling function with her object like fragmentB.itIsYourFunctionToUpdate() or
if (ViewPager.getCurrentItem() == 0 && page != null) {
          ((FragmentClass1)page).itIsYourFunctionToUpdate("new item");     
     }
  1. Also you can update viewPager like this mAdapter.notifyDataSetChanged() and all fragment inside viewPager must be updated
  • Related