我有以下代码:
activity_reminders.xml
<androidx.constraintlayout.widget.ConstraintLayout
xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:app="http://schemas.android.com/apk/res-auto"
xmlns:tools="http://schemas.android.com/tools"
android:layout_width="match_parent"
android:layout_height="match_parent"
tools:context=".locationreminders.RemindersActivity">
<fragment
android:id="@+id/nav_host_fragment"
android:name="androidx.navigation.fragment.NavHostFragment"
android:layout_width="match_parent"
android:layout_height="match_parent"
app:defaultNavHost="true"
app:navGraph="@navigation/nav_graph" />
</androidx.constraintlayout.widget.ConstraintLayout>
ReminderActivity.kt
class RemindersActivity : AppCompatActivity() {
private lateinit var binding: ActivityRemindersBinding
override fun onCreate(savedInstanceState: Bundle?) {
super.onCreate(savedInstanceState)
binding = ActivityRemindersBinding.inflate(layoutInflater)
setContentView(binding.root)
}
override fun onOptionsItemSelected(item: MenuItem): Boolean {
when (item.itemId) {
android.R.id.home -> {
(binding.navHostFragment as NavHostFragment).navController.popBackStack()
return true
}
}
return super.onOptionsItemSelected(item)
}
}
绑定。navHostFragment在未解决的,我不明白为什么,如果我改变视图的类型在任何不同,然后"碎片"视图绑定工作了。是否可以使用视图绑定在另一个视图内的片段?
我找到了以下作为获得片段的变通解决方案。
val navHostFragment = findNavController(R.id.nav_host_fragment)
navHostFragment.popBackStack()
我认为这是不可能使用
而不是:
(binding.navHostFragment as NavHostFragment).navController.popBackStack()
使用以下代码:
(supportFragmentManager.findFragmentById(R.id.nav_host_fragment) as NavHostFragment).navController.popBackStack()