使用Lottie的Android BottomNavigationView出现了动画问题

3

我正在尝试使用 BottomNavigationView 和 Lottie 库来制作图标动画。我更喜欢使用 Lottie 而不是 VectorAndroidAnimation,因为我想要更复杂的动画。然而,当我点击第一个 BottomNavigationView 项时,它不会进行动画,但其他项目会。

(见下方GIF)

with three items

以下是我的代码:

 class MainActivity : AppCompatActivity(), BottomNavigationView.OnNavigationItemSelectedListener {

    override fun onCreate(savedInstanceState: Bundle?) {
        super.onCreate(savedInstanceState)
        setContentView(R.layout.activity_main)
        val navView: BottomNavigationView = findViewById(R.id.nav_view)

        navView.menu.apply {
            add(Menu.NONE, 0, Menu.NONE, R.string.title_home).icon = getLottieDrawable(
                LottieAnimation.HOME,
                navView
            )
            add(Menu.NONE, 1, Menu.NONE, R.string.title_dashboard).icon = getLottieDrawable(
                LottieAnimation.CALENDAR,
                navView
            )
            add(Menu.NONE, 2, Menu.NONE, R.string.title_notifications).icon = getLottieDrawable(
                LottieAnimation.BELL,
                navView
            )
        }

        navView.setOnNavigationItemSelectedListener(this)
    }

    override fun onNavigationItemSelected(item: MenuItem): Boolean {
        val icon = item.icon as? LottieDrawable
        icon?.apply {
            playAnimation()
        }
        return true
    }

    private fun getLottieDrawable(
        animation: LottieAnimation,
        view: BottomNavigationView
    ): LottieDrawable {
        return LottieDrawable().apply {
            val result = LottieCompositionFactory.fromAssetSync(
                view.context.applicationContext, animation.value
            )
            callback = view
            composition = result.value
        }
    }

}

enum class LottieAnimation(val value: String) {
    HOME("home.json"),
    CALENDAR("calendar.json"),
    BELL("bell.json")
} 

仅使用两个项目进行BottomNavigationView测试,第一个选项卡的动画效果生效。

(下方为两个项目的Gif图)

with Two items

最后我使用了五个项目进行BottomNavigationView测试,在此测试中,当点击第一个和第二个项目时,它们不会有动画效果。只有选项卡中的最后三个项目才有动画效果。

with five items


你的问题有一个很棒的库,https://github.com/wwdablu/LottieBottomNav - Ahmet B.
2个回答

1

使用自定义底部导航视图如何?您可以在每个选项卡中添加一个Lottie视图,以便在单击时启动动画。根据我的经验,使用自定义底部导航视图比使用Android的底部导航视图效果更好。


0

我曾经遇到过同样的问题,那真是一场噩梦...但最终我找到了解决方案!

你必须在添加所有菜单项之后设置它们的图标。先进行第一次循环以添加你的菜单项,然后再进行第二次循环以设置每个全新菜单项的图标。

...
// First you add them ALL
add(Menu.NONE, 0, Menu.NONE, R.string.title_home)
add(Menu.NONE, 1, Menu.NONE, R.string.title_dashboard)
add(Menu.NONE, 2, Menu.NONE, R.string.title_notifications)

// Then you update their icons
findItem(0).icon = getLottieDrawable(
    LottieAnimation.HOME,
    navView
)
findItem(1).icon = getLottieDrawable(
    LottieAnimation.CALENDAR,
    navView
)
findItem(2).icon = getLottieDrawable(
    LottieAnimation.BELL,
    navView
)
...

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接