我正在尝试使用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不允许我使用此版本。
有人有什么想法吗?
谢谢!
答案 0 :(得分:0)
NavHostFragment
似乎是一个缺陷,似乎无法将数据向下传递到第一个片段,因为您可以将Bundle
设置为{{ 1}}函数将被覆盖。
最后,我通过在活动的第一个片段中构建捆绑包来解决此问题。我可以使用以下内容访问活动意图属性。
create
在这种情况下,这对我来说是足够的解决方法,但如果可能的话,那就太好了
答案 1 :(得分:0)
如果您使用的是视图模型,您可以这样做:
您的视图模型:
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
}
}