在 Compose BottomNavigation 中使用 AndroidFragment 重新创建

问题描述 投票:0回答:1

我有一个使用 Jetpack Compose 的 MainActivity 来设置带有 BottomBar 的脚手架。 BottomBar 管理一个包含可组合项的 NavHost,其中包括 AndroidFragment。

在选项卡之间切换时,我注意到片段被重新创建。我怎样才能保留片段,这样它们就不会重新加载数据?

internal fun NavGraph(
    navController: NavHostController,
    modifier: Modifier = Modifier
) {
    NavHost(
        navController = navController,
        modifier = modifier,
        startDestination = Screen.FrontPage
    ) {
        composable<Screen.FrontPage> {
            AndroidFragment(clazz = FrontPageFragment::class.java)
        }
        composable<Screen.LatestPage> {
            AndroidFragment(clazz = LatestPageFragment::class.java)
        }
    }
}
@AndroidEntryPoint
class MainActivity : BaseActivity() {

    override fun onCreate(savedInstanceState: Bundle?) {
        super.onCreate(savedInstanceState)
        setContent {
            Theme {
                Content()
            }
        }
    }
}

@Composable
private fun Content() {
    val navController = rememberNavController()
    var isSelectedIndex by rememberSaveable { mutableIntStateOf(0) }

    val screens = listOf(
        Screen.FrontPage,
        Screen.LatestPage
    )

    Scaffold(
        bottomBar = {
            NavigationBar() {
                screens.forEach { screen ->
                    val currentIndex = screens.indexOf(screen)
                    NavigationBarItem(
                        icon = {
                            Image(
                                painter = painterResource(screen.icon),
                                contentDescription = null
                            )
                        },
                        label = { Text(screen.title) },
                        selected = isSelectedIndex == currentIndex,
                        onClick = {
                          isSelectedIndex = currentIndex
                          navController.navigate(screen)
                        },
                    )
                }
            }
        },
        content = { innerPadding ->
            NavGraph(
                navController = navController,
                modifier = Modifier.padding(innerPadding)
            )
        }
    )
}
android android-jetpack-compose fragment
1个回答
0
投票

这个问题你解决了吗? ...

© www.soinside.com 2019 - 2024. All rights reserved.