1

I am trying to send information from fragment to the main activity.

I am trying to set a var interfaceName in a fragment from the main activity.

I created var menuInterface: MenuInterface and tried to set it in onNavigationItemSelected using myFragment.menuInterface = this

The menuInterface stays null for some reason... any idea why?

the onNavigationItemSelected

override fun onNavigationItemSelected(menuItem: MenuItem): Boolean {
    when (menuItem.itemId) {
        R.id.feedLayoutId -> {
            feedFragment = FeedFragment()
            feedFragment.menuInterface = this
            barTitle.text = "myTitle"
            supportFragmentManager
                .beginTransaction()
                .replace(R.id.frame_layout, feedFragment)
                .setTransition(FragmentTransaction.TRANSIT_FRAGMENT_OPEN)
                .commit()
        }
    }
    drawerLayout.closeDrawer(GravityCompat.START)
    return true
}
zion.b.
  • 71
  • 1
  • 8

2 Answers2

3

Implement MenuInterface in your activity,and remove this line from ur code.

feedFragment.menuInterface = this

In ur fragment:

private var menuInterface: MenuInterface? = null

override fun onAttach(context: Context?) {
    super.onAttach(context)
    menuInterface = context as MenuInterface
}

override fun onDetach() {
    menuInterface = null
    super.onDetach()
}
Prateek Kumar
  • 321
  • 1
  • 3
  • 16
0

I have already provided solution for such question. https://stackoverflow.com/a/35038574/3027124

The idea is communication between activity and fragment should be done through interfaces or you should implement MVVM architecture and use the same view model for both fragment and activity.

Useful resources:

Mustansar Saeed
  • 2,730
  • 2
  • 22
  • 46