如何在底部导航中将数据从MainActivity传递到主机Fragment数据?

时间:2019-07-22 13:50:10

标签: android android-jetpack android-jetpack-navigation

我在主活动中具有底部导航,并且在MainActivity中具有数据,我想将其传递给HostFragments我正在使用Google的NavigationExtensions形式来自Google NavigationAndvancedSample示例 这是我在MainActivity中使用的扩展功能,但是您知道我如何传递数据,这是将意图包含的数据传递给HostFragments的最佳方法?您可以看到我有fragmentTag和navigationHostFragment

fun BottomNavigationView.setupWithNavController(navGraphIds: List<Int>,
    fragmentManager: FragmentManager,containerId: Int,intent: Intent)



private fun obtainNavHostFragment(
    fragmentManager: FragmentManager,
    fragmentTag: String,
    navGraphId: Int,
    containerId: Int
): NavHostFragment {
  // If the Nav Host fragment exists, return it
  val existingFragment = fragmentManager.findFragmentByTag(fragmentTag) as NavHostFragment?
  existingFragment?.let { return it }

  // Otherwise, create it and return it.
  val navHostFragment = NavHostFragment.create(navGraphId)
  fragmentManager.beginTransaction()
      .add(containerId, navHostFragment, fragmentTag)
      .commitNow()
  return navHostFragment
}````





1 个答案:

答案 0 :(得分:0)

使用以下代码传递数据

Fragment fragment = findFragmentById(R.id.activity_content_4_fregment);
if (fragment instanceof Fragment_Class) {
    ((Fragment_Class) fragment).passdata(data);
}