【问题标题】:How can I pass data to the first Fragment whilst using the Navigation Architecture?如何在使用导航架构时将数据传递给第一个片段?
【发布时间】:2018-11-19 09:48:20
【问题描述】:

我正在尝试使用 NavHostFragment 将一组对象实例从我的主要活动传递到其他片段链中的第一个片段。我已经尝试了各种方法,但是一旦到达第一个片段,捆绑包似乎总是为空。

这是我启动 NavHostFragment 的方式(frameContainer 是我的布局 xml 中的框架容器元素)

NavHostFragment navHost = NavHostFragment.create(R.navigation.claim_nav_graph);
getSupportFragmentManager().beginTransaction()
        .replace(R.id.frameContainer, navHost)
        .setPrimaryNavigationFragment(navHost)
        .commit();

文档说有 2 个不同的 .create 函数,其中一个您可以将第二个参数作为包传递给其中一个,但 Android Studio 不允许我使用这个版本。

有人有什么想法吗?

提前致谢!

【问题讨论】:

  • 你发现了吗?它似乎缺少文档...

标签: android navigation fragment bundle


【解决方案1】:

这似乎是NavHostFragment 的一个缺陷,似乎不可能将数据向下传递到第一个片段,因为您可以将Bundle 设置为create 函数的第二个参数被覆盖一路走来。

最后,我通过在活动的第一个片段中构建捆绑包解决了这个问题。我能够使用以下内容访问活动意图属性。

// Kotlin
activity.intent?.extras?.getBundle(KEY_BUNDLE_ID)
// Java
getActivity().getIntent().getBundleExtra(KEY_BUNDLE_ID)

在这种情况下,这对我来说已经足够了,但如果可以的话,那就太好了

【讨论】:

    【解决方案2】:

    如果您使用 viewModels,您可以这样做:

    您的视图模型:

    class NiceViewModel: ViewModel() {
    
        var dataYouNeedToPass = "initialValue"
    
    }
    

    您的活动:

    class MainActivity : AppCompatActivity() {
    
        val niceViewModel: NiceViewModel by viewModels()
    
        override fun onCreate(savedInstanceState: Bundle?) {
            super.onCreate(savedInstanceState)
            setContentView(R.layout.activity_main)
    
            niceViewModel.dataYouNeedToPass = "data You Need To Pass"
    
        }
    
    }
    

    你的片段:

    class YourFragment : Fragment() {
    
        private lateinit var niceViewModel: NiceViewModel
    
    
        override fun onViewCreated(view: View, savedInstanceState: Bundle?) {
            super.onViewCreated(view, savedInstanceState)
    
            niceViewModel = (activity as MainActivity).niceViewModel
            niceViewModel.dataYouNeedToPass //do whatever you need to do with this
        
        }
    
    
    }
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2018-10-24
      • 2020-08-06
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2019-05-23
      • 2022-01-07
      相关资源
      最近更新 更多