为了在切换底部标签时不销毁Fragment视图,可以使用以下代码。
首先,我们需要在MainActivity中定义NavController,并使用onSaveInstanceState保留当前Fragment的状态。
class MainActivity : AppCompatActivity() {
private lateinit var navController: NavController
override fun onCreate(savedInstanceState: Bundle?) {
super.onCreate(savedInstanceState)
setContentView(R.layout.activity_main)
// Initialize NavController
navController = Navigation.findNavController(this, R.id.nav_host_fragment)
if (savedInstanceState == null) {
navController.navigate(R.id.homeFragment)
}
}
override fun onSaveInstanceState(outState: Bundle) {
super.onSaveInstanceState(outState)
Navigation.findNavController(this, R.id.nav_host_fragment).let {
outState.putInt("currentDestinationId", it.currentDestination?.id ?: R.id.homeFragment)
}
}
override fun onRestoreInstanceState(savedInstanceState: Bundle) {
super.onRestoreInstanceState(savedInstanceState)
Navigation.findNavController(this, R.id.nav_host_fragment).apply {
val currentDestinationId = savedInstanceState.getInt("currentDestinationId", R.id.homeFragment)
if (currentDestination?.id != currentDestinationId) {
navigate(currentDestinationId)
}
}
}
override fun onSupportNavigateUp(): Boolean {
return navController.navigateUp() || super.onSupportNavigateUp()
}
}
接下来,在Fragment中使用onCreateView和onDestroyView来保存和恢复Fragment视图的状态。
class MyFragment : Fragment() {
private var hasViewCreated: Boolean = false
override fun onCreateView(inflater: LayoutInflater, container: ViewGroup?, savedInstanceState: Bundle?): View? {
val view = inflater.inflate(R.layout.fragment_my, container, false)
if (!hasViewCreated) {
// Do initialization here
hasViewCreated = true
} else {
// Restore state here
}
return view
}
override fun onDestroyView() {
super.onDestroyView()
hasViewCreated = false
}
}
当Fragment视图被创建时,我们进行初始化。当Fragment被销毁并重新创建时,我们将恢复保存的状态。在每个Fragment中使用这些代码来存储和恢复Fragment视图状态,就可以在切换底部标签时不销毁Fragment视图了。