会动的底部导航栏-Lottie的应用

简介:随着Android的发展,用户审美的不断提高,你的app不仅得足够好用,UI也得让人感觉赏心悦目,今天无意间打开CSDN看帖子时,发现点击底部导航栏时,图标是会播放动画的,一时好奇是如何实现的,然后就浅浅的研究了下~

CSDN效果图

实现效果

话不多说,让我们开始吧~

首先介绍下Lottie这个库,可以帮助开发者更简单的实现复杂的动画效果

依赖:

implementation 'com.airbnb.android:lottie:6.4.0'

LottieView.kt

package com.xcy.mylottietab

import android.content.Context
import android.content.res.TypedArray
import android.util.AttributeSet
import android.widget.Checkable
import com.airbnb.lottie.LottieAnimationView

/**
 * 播放Json动画的View
 */
class LottieView(context: Context?, attrs: AttributeSet?) : LottieAnimationView(context, attrs),
    Checkable {

    private var checked: Boolean = false
    private var mode: Mode = Mode.Light //默认白天主题
    private var lightAnimationPath: String? = "" //白天主题的动画文件路径
    private var nightAnimationPath: String? = "" //夜晚主题的动画文件路径

    enum class Mode {
        Light, Night
    }

    init {
        var typedArray: TypedArray = context!!.obtainStyledAttributes(attrs, R.styleable.LottieView)

        setAnimationPath(typedArray.getString(R.styleable.LottieView_lightAnimationPath),true)
        setAnimationPath(typedArray.getString(R.styleable.LottieView_nightAnimationPath),false)
    }

    fun setAnimationPath(animationPath: String?, isLight: Boolean) {
        if (animationPath.isNullOrEmpty()) {
            throw NullPointerException("LottieView animationPath is empty.")
        }
        if (isLight) {
            this.lightAnimationPath = animationPath
        } else {
            this.nightAnimationPath = animationPath
        }
        selectAnimation()
    }

    private fun selectAnimation(){
        if (mode == Mode.Light){
            setAnimation(lightAnimationPath)
        }else if (mode == Mode.Night){
            setAnimation(nightAnimationPath)
        }
    }

    fun selectMode(mode : Mode){
        this.mode = mode
        selectAnimation()
    }

    override fun setChecked(checked: Boolean) {
        try {
            if (this.checked != checked) {
                this.checked = checked
                if (isAnimating) {
                    cancelAnimation()
                }
                if (checked) {
                    if (speed < 0.0F) {
                        reverseAnimationSpeed();
                    }
                    playAnimation()
                } else {
                    cancelAnimation()
                    progress = 0f
                }
            }
        } catch (e: Exception) {
            e.printStackTrace()
        }
    }

    override fun isChecked(): Boolean {
        return checked
    }

    override fun toggle() {
        isChecked = !checked
    }
}

MainActivity.kt

package com.xcy.mylottietab

import android.annotation.SuppressLint
import android.os.Bundle
import android.os.PersistableBundle
import android.view.View
import android.view.View.OnClickListener
import android.widget.LinearLayout
import android.widget.Switch
import androidx.appcompat.app.AppCompatActivity

class MainActivity : AppCompatActivity(), OnClickListener {

    private var savedInstanceState: Bundle? = null

    private lateinit var swTopic: Switch
    private lateinit var llNavigation: LinearLayout
    private lateinit var tabHome: LottieView
    private lateinit var tabC: LottieView
    private lateinit var tabMessage: LottieView
    private lateinit var tabMine: LottieView

    private var tabs = arrayListOf<LottieView>()
    private val NAVIGATION_INDEX_KEY = "NAVIGATION_INDEX_KEY"
    private var NAVIGATION_INDEX = 0

    @SuppressLint("MissingInflatedId")
    override fun onCreate(savedInstanceState: Bundle?) {
        super.onCreate(savedInstanceState)
        this.savedInstanceState = savedInstanceState

        setContentView(R.layout.activity_main)

        swTopic = findViewById(R.id.sw_topic)
        llNavigation = findViewById(R.id.ll_navigation)
        tabHome = findViewById(R.id.tab_home)
        tabC = findViewById(R.id.tab_c)
        tabMessage = findViewById(R.id.tab_message)
        tabMine = findViewById(R.id.tab_mine)

        //Add Tab
        tabs.add(tabHome)
        tabs.add(tabC)
        tabs.add(tabMessage)
        tabs.add(tabMine)

        //设置home为默认选中
        setChecked(tabHome.id)

        //风格切换
        swTopic.setOnCheckedChangeListener { buttonView, isChecked ->
            setMode()
        }
    }

    override fun onSaveInstanceState(outState: Bundle) {
        super.onSaveInstanceState(outState)
        //防止Activity重建,导致LottieView选中状态异常
        outState.putInt(NAVIGATION_INDEX_KEY, getChecked())
    }

    override fun onResume() {
        super.onResume()
        //判断是否需要恢复Activity重建前的选中状态
        savedInstanceState?.let {
            try {
                var selectIndex = it.getInt(NAVIGATION_INDEX_KEY, 0)
                setChecked(tabs[selectIndex].id)
            } catch (e: IndexOutOfBoundsException) {
                e.printStackTrace()
            }
        }
    }

    override fun onClick(v: View?) {
        when (v!!.id) {
            R.id.tab_home, R.id.tab_c, R.id.tab_message, R.id.tab_mine -> {
                setChecked(v.id)
            }
        }
    }

    /**
     * 主题切换
     */
    private fun setMode() {
        var mode: LottieView.Mode

        if (!swTopic.isChecked) {
            mode = LottieView.Mode.Light
            llNavigation.setBackgroundResource(R.color.white)
        } else {
            mode = LottieView.Mode.Night
            llNavigation.setBackgroundResource(R.color.color_1B1B27)
        }

        //批量设置主题
        tabs.forEach {
            it.selectMode(mode)
        }
    }

    /**
     * 选中某个LottieView
     * @param resId 需要被选中的LottieView的资源id
     */
    private fun setChecked(resId: Int) {
        //清除当前的选中状态
        tabs.forEach { lottieView ->
            lottieView.isChecked = false
        }
        //设置某一个LottieView为选中
        tabs.forEach { lottieView ->
            if (lottieView.id == resId) {
                lottieView.isChecked = true
                return@forEach
            }
        }
    }

    /**
     * 获取当前的选中状态
     * @param return 返回被选中的LottieView下标
     */
    private fun getChecked(): Int {
        tabs.forEachIndexed { index, lottieView ->
            if (lottieView.isChecked) {
                return index
            }
        }
        return -1
    }
}

activity_main.xml

<?xml version="1.0" encoding="utf-8"?>
<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"
    android:background="#CCC"
    tools:context=".MainActivity">

    <Switch
        android:id="@+id/sw_topic"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:text="夜间主题"
        app:layout_constraintBottom_toTopOf="@id/ll_navigation"
        app:layout_constraintLeft_toLeftOf="parent"
        app:layout_constraintRight_toRightOf="parent"
        app:layout_constraintTop_toTopOf="parent" />

    <LinearLayout
        android:id="@+id/ll_navigation"
        android:background="@android:color/white"
        android:layout_width="match_parent"
        android:layout_height="45dp"
        android:orientation="horizontal"
        android:weightSum="4"
        app:layout_constraintBottom_toBottomOf="parent"
        app:layout_constraintLeft_toLeftOf="parent"
        app:layout_constraintRight_toRightOf="parent">

        <com.xcy.mylottietab.LottieView
            android:id="@+id/tab_home"
            android:layout_width="0dp"
            android:layout_height="match_parent"
            android:layout_weight="1"
            android:onClick="onClick"
            app:lightAnimationPath="home_tabbar_d.json"
            app:nightAnimationPath="home_tabbar_n.json" />

        <com.xcy.mylottietab.LottieView
            android:id="@+id/tab_c"
            android:layout_width="0dp"
            android:layout_height="match_parent"
            android:layout_weight="1"
            android:onClick="onClick"
            app:lightAnimationPath="wk_tabbar_d.json"
            app:nightAnimationPath="wk_tabbar_n.json" />

        <com.xcy.mylottietab.LottieView
            android:id="@+id/tab_message"
            android:layout_width="0dp"
            android:layout_height="match_parent"
            android:layout_weight="1"
            android:onClick="onClick"
            app:lightAnimationPath="msg_tabbar_d.json"
            app:nightAnimationPath="msg_tabbar_n.json" />

        <com.xcy.mylottietab.LottieView
            android:id="@+id/tab_mine"
            android:layout_width="0dp"
            android:layout_height="match_parent"
            android:layout_weight="1"
            android:onClick="onClick"
            app:lightAnimationPath="me_tabbar_d.json"
            app:nightAnimationPath="me_tabbar_n.json" />

    </LinearLayout>

</androidx.constraintlayout.widget.ConstraintLayout>

attrs.xml

<?xml version="1.0" encoding="utf-8"?>
<resources>
    <declare-styleable name="LottieView">
        <attr name="lightAnimationPath" format="string"></attr>
        <attr name="nightAnimationPath" format="string"></attr>
    </declare-styleable>
</resources>

文中提到的json动画文件在这里~

https://gitee.com/xcy_god/my-lottie-tab/tree/master/app/src/main/assets

文中的json动画文件源自于反编译 CSDN app,如有侵权,联系删除~

代码链接 <=====需要源代码的小伙伴可自取

  • 5
    点赞
  • 4
    收藏
    觉得还不错? 一键收藏
  • 打赏
    打赏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

徐小歌

你的鼓励将是我创作的最大动力

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值