会动的底部导航栏-Lottie的应用-程序员宅基地

技术标签: android  

简介:随着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,如有侵权,联系删除~

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

版权声明:本文为博主原创文章,遵循 CC 4.0 BY-SA 版权协议,转载请附上原文出处链接和本声明。
本文链接:https://blog.csdn.net/qq_34453595/article/details/137750198

智能推荐

spring-boot3-程序员宅基地

文章浏览阅读112次。更多的配置:# ===================================================================# COMMON SPRING BOOT PROPERTIES## This sample file is provided as a guideline. Do NOT copy it in its# entire..._call: services/json/configure/testconnection -------------------------------

基于ssm+vue的校园驿站管理系统+(源码+部署说明+演示视频+源码介绍)-程序员宅基地

文章浏览阅读1k次,点赞14次,收藏10次。基于ssm+vue的校园驿站管理系统+(源码+部署说明+演示视频+源码介绍).zip

div内容超出容器宽度,超出显示省略号且鼠标悬浮显示全部内容_div设置省略号-程序员宅基地

文章浏览阅读946次,点赞8次,收藏10次。div内容超出容器宽度,超出部分显示省略号且鼠标悬浮显示全部内容_div设置省略号

Python类的重写和私有变量_重写方法其中的self变量怎么写-程序员宅基地

文章浏览阅读293次。1)类的重写# 如果子类想实现父类构造器中的方法,然后自己再写自己特殊的方法,便需要调用父类的__init__()方法class parent(object): # 定义父类的时候,一定要写继承object类,否则会报错 name = 'parent' sex = 'F' def __init__(self,address,age): self._重写方法其中的self变量怎么写

「Python」提取json数据为txt格式成功_python接口返回json数据是text格式-程序员宅基地

文章浏览阅读3k次,点赞2次,收藏10次。步骤1、你要检查json文件利用专门的解析json文件的网站校验进行https://www.sojson.com/2、不符合JSON语法格式的会报错,这时需要修改,直到正确3、Python读取一、JSON 语法规则数据在名称/值对中数据由逗号分隔花括号保存对象方括号保存数组举例问题:它报错说逗号有问题,其实不是,问题出在缺少中括号。在最外层补充中括号,JSON文件就没问题了。二、Python读取json数据完整正确的代码:import jsonfile=r'中国合作t_python接口返回json数据是text格式

编码规范_源代码 编码规范 调研表-程序员宅基地

文章浏览阅读924次。1.4.B 编码规范——如何写出简洁优美的代码 下面是来自两位C语言程序员的实现相同功能的两段代码: l 月薪1000元的程序员的代码: #include int main() { FILE *Wenjian; char Str[100]; Wenjian = fopen("test.txt","w"); do_源代码 编码规范 调研表

随便推点

【软件设计师备考 专题 】软件过程改进:提升软件开发效率和质量_为什么要进行软件过程改进-程序员宅基地

文章浏览阅读248次。软件过程改进是指通过对软件开发过程的分析、评估和优化,以提高软件开发效率和质量的一系列活动。它包括对软件开发过程的规范、流程、工具和方法的改进,旨在使软件开发过程更加高效、可控和可持续。_为什么要进行软件过程改进

jdk1.6环境下使用springboot的配置-程序员宅基地

文章浏览阅读774次。2019独角兽企业重金招聘Python工程师标准>>> ..._springboot配置jdk1.6

解决‘error_code‘: 110, ‘error_msg‘: ‘Access token invalid or no longer valid(百度智能云使用方法)-程序员宅基地

文章浏览阅读1.2w次,点赞2次,收藏6次。解决’error_code’: 110, ‘error_msg’: 'Access token invalid or no longer valid(百度智能云使用方法)出现上述错误,是因为没有将例子中的access token的结果进行正确替换。具体做法如下:搜索百度智能云,注册登录以车牌识别为例:产品>汽车场景文字识别>立即使用>创建应用(归属选个人,免费)>查看详细信息(生成AD AK SK,将其复制)>使用方式>API文档获取accrss token_access token invalid or no longer valid

AES加密_aes加密 csdn-程序员宅基地

文章浏览阅读339次,点赞5次,收藏10次。密钥交换算法是指在不安全的通道上,通过某种算法交换一个密钥,常用的有Diffie-Hellman(DH)算法、椭圆曲线Diffie-Hellman(ECDH)算法等。消息摘要算法是一种单向加密算法,将任意长度的数据转换成固定长度的输出,常用的有MD5、SHA-1、SHA-2等。数字签名算法是将消息或数据进行哈希计算,然后用私钥签名,验证签名时使用公钥进行验证,常用的有RSA、DSA等。非对称加密算法使用一对密钥(公钥和私钥)对数据进行加密和解密,常用的有RSA、DSA、ECC等。3、确保数据的完整性。_aes加密 csdn

电脑C盘缓存清理全攻略:手把手教你如何安全有效地释放系统空间_qindows清理c盘最终版-程序员宅基地

文章浏览阅读561次,点赞3次,收藏3次。随着计算机使用时间的增长,C盘(系统盘)中的临时文件、系统缓存和日志等数据会逐渐累积,占用大量磁盘空间,导致系统运行速度减慢。定期对C盘进行缓存清理是保持系统健康与高效的重要维护工作。本文将详细介绍如何安全且有效地清理C盘中的各类缓存,帮助用户释放宝贵的存储资源。_qindows清理c盘最终版

python中怎么获取js的输出值_使用Python中的BeautifulSoup在HTML源代码中获取JS var值(Get JS var value in HTML source using Be...-程序员宅基地

文章浏览阅读1.2k次。使用Python中的BeautifulSoup在HTML源代码中获取JS var值(Get JS var value in HTML source using BeautifulSoup in Python)我正在尝试使用BeautifulSoup从HTML源代码中获取JavaScript var值。例如我有:[other code]var my = 'hello';var name = 'hi'..._python 取得js返回值