使用 Compose 在导航中的 Composable 之间制作动画

Ahm*_*out 11 android android-jetpack-compose

我已经开始尝试使用导航进行撰写。

我创建了我的 2 Composables,一切正常。

但我缺少的是页面之间的动画(或过渡)。我没有找到任何资源指出如何在 Compose 中做到这一点。

我知道所有动画都基于 Compose 中的状态,但我唯一知道的是导航返回堆栈。

cku*_*der 12

Accompanist版本0.16.1及以上支持目的地之间的动画。这是有关更多信息的文章。

implementation("com.google.accompanist:accompanist-navigation-animation:0.16.1")  
Run Code Online (Sandbox Code Playgroud)
import com.google.accompanist.navigation.animation.AnimatedNavHost
import com.google.accompanist.navigation.animation.composable
import com.google.accompanist.navigation.animation.rememberAnimatedNavController


val navController = rememberAnimatedNavController()

AnimatedNavHost(navController, startDestination = "first") {
    composable(
        route = "first",
        enterTransition = { _, _ -> slideInHorizontally(animationSpec = tween(500)) },
        exitTransition = { _, _ -> slideOutHorizontally(animationSpec = tween(500)) }
    ) {
       FirstScreen()
    }
    composable(
        route = "second",
        enterTransition = { _, _ -> slideInHorizontally(initialOffsetX = { it / 2 }, animationSpec = tween(500)) },
        exitTransition = { _, _ -> slideOutHorizontally(targetOffsetX = { it / 2 }, animationSpec = tween(500)) }
    ) {
       SecondScreen()
    }
}
Run Code Online (Sandbox Code Playgroud)

结果:

在此输入图像描述


Кон*_*кин 8

您可以使用我制作的可组合来显示进入动画(在“进入”和“退出”参数中配置首选效果)

fun EnterAnimation(content: @Composable () -> Unit) {
    AnimatedVisibility(
        visible = true,
        enter = slideInVertically(
            initialOffsetY = { -40 }
        ) + expandVertically(
            expandFrom = Alignment.Top
        ) + fadeIn(initialAlpha = 0.3f),
        exit = slideOutVertically() + shrinkVertically() + fadeOut(),
        content = content,
        initiallyVisible = false
    )
}
Run Code Online (Sandbox Code Playgroud)

你可以这样使用它:

NavHost(
    navController = navController,
    startDestination = "dest1"
) {
    composable("dest1") {
        EnterAnimation {
            FirstScreen(navController)
        }
    }
    composable("dest2") {
        EnterAnimation {
            SecondScreen(navController)
        }
    }
}
Run Code Online (Sandbox Code Playgroud)


ngl*_*ber 6

在 alpha-09 中,这不受支持。:(

请为这个问题加注星标:https : //issuetracker.google.com/issues/172112072


小智 5

由于昨天的更新(版本2.4.0-alpha05):

\n

导航 Compose\xe2\x80\x99s NavHost 现在在导航目的地时始终使用 Crossfades。

\n