【问题标题】:Kotlin opening new fragment in nav drawer exampleKotlin 在导航抽屉示例中打开新片段
【发布时间】:2021-04-18 11:17:10
【问题描述】:

我对 Kotlin 比较陌生,我正在尝试通过在我的片段中添加一个按钮来扩展导航抽屉示例,该按钮可以直接打开另一个片段,而无需从导航抽屉中选择它。 这是我片段的onCreateView 函数中的按钮侦听器:

    addButton.setOnClickListener()
    {
        Toast.makeText(this.context,"ButtonPressed",Toast.LENGTH_SHORT).show()
        this.activity.supportFragmentManager.beginTransaction().replace(R.id.mobile_navigation, R.layout.fragment2).commit()
    }

我不确定我是否完全理解如何处理这个问题。该按钮工作正常并调用 toast,但我无法让它更改片段。

任何帮助将不胜感激。

【问题讨论】:

  • 你使用导航架构组件吗?
  • 不确定。虽然模板有一个带有“导航”元素的 mobile_navigation.xml 文件。我已经想出了如何将新片段添加到导航抽屉中,但我正在尝试通过片段类代码中的按钮和函数来更改当前片段。

标签: android kotlin android-fragments android-architecture-components android-navigation


【解决方案1】:

模板有一个带有“导航”元素的 mobile_navigation.xml 文件。

Navigation Architecture components 在最近的 android studio 版本中默认使用,因此 navController 负责片段事务,而不是由 supportFragmentManager 手动执行

addButton.setOnClickListener() {
    Toast.makeText(this.context,"ButtonPressed",Toast.LENGTH_SHORT).show()

    val navHostFragment = requireActivity().supportFragmentManager
        .primaryNavigationFragment as NavHostFragment

    navHostFragment.navController.navigate(R.layout.fragment2)
}

另外,确保R.layout.fragment2R.id.mobile_navigation.xml 中目标片段的片段ID

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2020-06-01
    • 1970-01-01
    • 1970-01-01
    • 2013-12-16
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多