Android仿iOS底部弹出菜单ActionSheet-程序员宅基地

技术标签: 底部菜单  UI  仿Ios  菜单  

由于产品是个果婊,有时候为了统一app风格,需要被迫使用ios风格的系统控件,比较常见的就是ios 的底部弹出菜单,在网上找了很久都没有找到还原度很高的,就自己动手写了,为了以防万一以后再有这类需求,这里把大致实现思路和代码献上,有需要的自己copy就行了。

成品图:

这里写图片描述

UI层级

这里写图片描述
具体都写在图上了,考虑到性能因素,viewGroup继承自FrameLayout,contentGroup、menuList继承自LinearLayout、CancelButton继承自TextView。

核心思想

  • 采用伪Build模式编写,之所以说伪Build是因为没有严格按照模式框架来编写,但是对外调用和Build相似。
  • 运用了Toast模式,直接将布局添加到Window下DecorView中,可以在任意Activity中调用,不需要改动原本View或者进行View绑定。

源代码

class IosBottomListWindow(private val activity: Activity) {
    private val shadowMax = 0xa0
    private var majorTitle: TextView? = null
    private var title: TextView? = null
    private val viewGroup: FrameLayout
    private val contentGroup: LinearLayout
    private val menuList: LinearLayout
    private val commonMargin = dpToPx(10f, activity).toInt()
    private val itemMargin = dpToPx(16f, activity).toInt()
    private var contentLayoutHeight = 0

    var isShow = false

    init {
        viewGroup = initViewGroup()
        contentGroup = initContentGroup()
        menuList = initMenuList()
        viewGroup.addView(contentGroup)
        contentGroup.addView(menuList)
    }

    fun show() {
        if (!isShow) {
            (activity.window.decorView as ViewGroup).addView(viewGroup)
            contentGroup.apply {
                post {
                    contentLayoutHeight = measuredHeight
                    translationY = contentLayoutHeight.toFloat()
                    visibility = View.VISIBLE
                    startAnimator(true)
                }
            }
            isShow = true
        }
    }

    fun dismiss() {
        if (isShow) {
            startAnimator(false, object : SimpleAnimListener() {
                override fun onAnimationEnd(animation: Animator?) {
                    (activity.window.decorView as ViewGroup).removeView(viewGroup)
                }
            })
            isShow = false
        }
    }

    /**
     * 设置主标题
     */
    fun setMajorTitle(text: String): IosBottomListWindow {
        majorTitle = TextView(activity).apply {
            layoutParams = LinearLayout.LayoutParams(LinearLayout.LayoutParams.WRAP_CONTENT,
                    LinearLayout.LayoutParams.WRAP_CONTENT).apply {
                val margin = dpToPx(20f, activity).toInt()
                if (title == null) {
                    setMargins(0, margin, 0, margin)
                } else {
                    setMargins(0, margin, 0, 0)
                }
            }
            setTextSize(TypedValue.COMPLEX_UNIT_SP, 14f)
            setTextColor(Color.parseColor("#8f8f8f"))
            typeface = Typeface.DEFAULT_BOLD
            setText(text)
        }
        menuList.addView(majorTitle, 0)
        return this
    }

    /**
     * 设置副标题
     */
    fun setTitle(text: String): IosBottomListWindow {
        title = TextView(activity).apply {
            layoutParams = LinearLayout.LayoutParams(LinearLayout.LayoutParams.WRAP_CONTENT,
                    LinearLayout.LayoutParams.WRAP_CONTENT).apply {
                val margin = dpToPx(20f, activity).toInt()
                if (majorTitle == null) {
                    setMargins(0, margin, 0, margin)
                } else {
                    setMargins(0, 0, 0, margin)
                }
            }
            setTextSize(TypedValue.COMPLEX_UNIT_SP, 14f)
            setTextColor(Color.parseColor("#8f8f8f"))
            setText(text)
        }
        if (majorTitle == null) {
            menuList.addView(title, 0)
        } else {
            menuList.addView(title, 1)
        }
        return this
    }

    /**
     * 设置子项
     */
    fun setItem(text: String, textColor: Int = 0, itemClickListener: () -> Unit): IosBottomListWindow {
        val textView = TextView(activity)
        textView.apply {
            layoutParams = LinearLayout.LayoutParams(LinearLayout.LayoutParams.MATCH_PARENT,
                    LinearLayout.LayoutParams.WRAP_CONTENT).apply {
                setPadding(0, itemMargin, 0, itemMargin)
            }
            gravity = Gravity.CENTER
            setBackgroundResource(R.drawable.command_bg_click_xml)
            setTextSize(TypedValue.COMPLEX_UNIT_SP, 20f)
            if (textColor == 0) {
                setTextColor(Color.parseColor("#FF3B30"))
            } else {
                try {
                    setTextColor(textColor)
                } catch (e: Throwable) {
                    e.printStackTrace()
                }
            }
            setText(text)
            setOnClickListener {
                itemClickListener.invoke()
                dismiss()
            }
        }
        val lineView = View(activity).apply {
            layoutParams = LinearLayout.LayoutParams(LinearLayout.LayoutParams.MATCH_PARENT, 1)
            setBackgroundColor(Color.parseColor("#dcdbdf"))
        }
        menuList.addView(lineView)
        menuList.addView(textView)
        return this
    }

    /**
     * 设置按钮
     */
    fun setCancelButton(text: String, textColor: Int = 0): IosBottomListWindow {
        val cancelView = TextView(activity).apply {
            layoutParams = LinearLayout.LayoutParams(LinearLayout.LayoutParams.MATCH_PARENT,
                    LinearLayout.LayoutParams.WRAP_CONTENT).apply {
                setMargins(commonMargin, 0, commonMargin, commonMargin)
            }
            setPadding(0, itemMargin, 0, itemMargin)
            background = resources.getDrawable(R.drawable.bottom_btn_click_xml, null)
            if (textColor == 0) {
                setTextColor(Color.parseColor("#FF3B30"))
            } else {
                try {
                    setTextColor(textColor)
                } catch (e: Throwable) {
                    e.printStackTrace()
                }
            }
            gravity = Gravity.CENTER
            setTextSize(TypedValue.COMPLEX_UNIT_SP, 20f)
            setText(text)
            typeface = Typeface.DEFAULT_BOLD
            setOnClickListener {
                dismiss()
            }
        }
        contentGroup.addView(cancelView)
        return this
    }

    /**
     * 初始化容器
     * 背景阴影容器
     */
    private fun initViewGroup() = FrameLayout(activity).apply {
        layoutParams = ViewGroup.LayoutParams(ViewGroup.LayoutParams.MATCH_PARENT,
                ViewGroup.LayoutParams.MATCH_PARENT)
        setOnClickListener {
            dismiss()
        }
    }

    /**
     * 初始化内容容器
     * 滑动动画载体
     */
    private fun initContentGroup() = LinearLayout(activity).apply {
        layoutParams = FrameLayout.LayoutParams(FrameLayout.LayoutParams.MATCH_PARENT,
                FrameLayout.LayoutParams.WRAP_CONTENT).apply {
            gravity = Gravity.BOTTOM
            bottomMargin = getBottomStatusHeight(activity)
            visibility = View.INVISIBLE
        }
        orientation = LinearLayout.VERTICAL
    }

    /**
     * 初始化菜单列表
     */
    private fun initMenuList() = LinearLayout(activity).apply {
        layoutParams = LinearLayout.LayoutParams(LinearLayout.LayoutParams.MATCH_PARENT,
                LinearLayout.LayoutParams.WRAP_CONTENT).apply {
            setMargins(commonMargin, 0, commonMargin, commonMargin)
        }
        gravity = Gravity.CENTER_HORIZONTAL
        orientation = LinearLayout.VERTICAL
        background = activity.resources.getDrawable(R.drawable.shape_bottom_list_menu, null)
    }

    private fun startAnimator(enterType: Boolean, listener: Animator.AnimatorListener? = null) {
        viewGroup.post {
            ValueAnimator().apply {
                if (enterType) {
                    setFloatValues(contentLayoutHeight.toFloat(), 0f)
                } else {
                    setFloatValues(0f, contentLayoutHeight.toFloat())
                }
                duration = 300
                interpolator = DecelerateInterpolator()
                addUpdateListener {
                    val value = it.animatedValue as Float
                    contentGroup.translationY = value
                    setShadow()
                }
                listener?.let {
                    addListener(it)
                }
                start()
            }
        }
    }

    private fun setShadow() {
        val ratio = contentGroup.translationY / contentLayoutHeight
        val shadow = (shadowMax * (1 - ratio)).toInt()
        if (shadow >= 16) {
            viewGroup.setBackgroundColor(Color.parseColor("#${shadow.toString(16)}000000"))
        }
    }

}

用到资源文件

shape_bottom_list_menu.xml
<shape xmlns:android="http://schemas.android.com/apk/res/android">
    <corners android:radius="15dp"/>
    <solid android:color="#f1f1f1"/>
</shape>

bottom_btn_click.xml
<ripple xmlns:android="http://schemas.android.com/apk/res/android"
        android:color="@color/ColorRipe">
    <item android:drawable="@drawable/shape_bottom_list_button"/>
</ripple>

shape_bottom_list_button.xml
<shape xmlns:android="http://schemas.android.com/apk/res/android">
    <corners android:radius="15dp"/>
    <solid android:color="#ffffff"/>
</shape>

调用

            IosBottomListWindow(this)
                    .setTitle("上传头像")
                    .setMajorTitle("上传头像")
                    .setItem("从相册", resources.getColor(R.color.color_c10)) {
                        getPhotoFromAlbum()
                    }
                    .setItem("从相机") {
                        dispatchTakePictureIntent()
                    }
                    .setCancelButton("取消")
                    .show()

最后

如果该文章对你有帮助,希望能顺手点个赞或者收藏。Σ(*゚д゚ノ)ノ

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

智能推荐

Linux使用docker搭建Mysql主从复制_linux 实现docker的mysql主从复制-程序员宅基地

文章浏览阅读326次。Linux使用docker搭建Mysql主从复制_linux 实现docker的mysql主从复制

C++ :error C3872: '0x3000': this character is not allowed in an identifier 包含中文全角空格错误【已解决】_character <u+ff08> not allowed in an identifier-程序员宅基地

文章浏览阅读870次。error C3872: ‘0x3000’: this character is not allowed in an identifier写的serialdll.cpp文件中报错如下,一大堆错误,但是反复查看了那几行代码,甚至重新写了一遍,还是报错。在网上帖子说可能是代码中有中文的全角空格,导致报错。但使用Ctrl + H查找当前的cpp文件,完全没有找到中文全角空格;继续排查原因,发现..._character not allowed in an identifier

解决Mac下MX4手机无法连接adb问题之解决方案-程序员宅基地

文章浏览阅读46次。一般的android连接mac 很方便不用安装驱动就可以啦,可是不知道为什么特殊情况下有的android手机(小米2,华为等)就是连接不上,下来就说说特殊情况下如何连接。使用USB连接安卓手机后可以做2件事情:1.关于本机-->更多信息->概系统览->系统报告->usb->你所连接的device-->供应商ID(Vendor ID)2..打开终端,输..._macpro adb连接mix4

老花眼:男女的“更年期”-程序员宅基地

文章浏览阅读671次。What do you think, how many operations can be done on one eye? A clinical case of one of my patients confirms that more than 20 operations of various kinds are not the limit. Although, no doubt, thi..._更年期 眼压高

MongoDB索引详解_mongodb索引的数据结构-程序员宅基地

文章浏览阅读1.2k次,点赞15次,收藏9次。MongoDB索引详解_mongodb索引的数据结构

SWAN之ikev2/acert-inline测试_ikev2测试向量-程序员宅基地

文章浏览阅读369次。本测试中远程用户(roadwarrior)carol和dave与网关moon建立连接。认证方式基于X.509证书,为了对远程用户进行授权,moon网关期望用户在IKEv2报文的CERT载荷中带有属性证书。carol主机具有合法的证书,但是dave提供的是两个无效属性证书:一个证书不是用于sales组;另外一个是由已过期的AA所签发。以下启动ikev2/acert-inline测试用例,注意在启动..._ikev2测试向量

随便推点

qt 实现RTSP&RTMP拉流,实时显示视频流_qt rtsp拉流-程序员宅基地

文章浏览阅读2.5w次,点赞22次,收藏202次。最近项目需求,要实现一个rtsp视频流,经过一番了解之后,最后选择两种方式进行测试对比,一个是基于ffmpeg编码实现rtsp拉流,另外一个则是基于VLC开源的qt第三方库,实在github上搜索到的 key: qt vlc。首先粗略讲下ffmpeg编码怎么实现rtsp拉流呢?没有接触之前,感觉很高深的样子,其实并不然,ffmpeg内部基本都帮你实现了,类似打开摄像头一样的流程,使用avfor..._qt rtsp拉流

Java操作本地windows系统的cmd命令-程序员宅基地

文章浏览阅读10w+次,点赞2次,收藏11次。人工智能,零基础入门!http://www.captainbed.net/inner一、windows系统下运行cmd命令,直接打开cmd窗口输入对应命令执行就可以了,步骤:【1】输入快捷键:windows + R,如何输入cmd,按回车【2】然后会进入cmd命令的窗口界面:【3】执行一些cmd命令,看效果如下显示:二、但是在Java程序中如何执行本地windo...

使用WPUSH实现每日60s早报新闻的推送-程序员宅基地

文章浏览阅读403次,点赞6次,收藏7次。ALAPI:是一个免费的API接口平台,里面集成了上百个免费API接口WPUSH: 一个聚合消息推送平台,可以推送微信、短信、邮件、飞书、钉钉等消息Github Actions: 自动化CI工具,可以用这个实现自动化构建、定时任务等。_每日60s

基于Python所写的火车票分析助手设计_基于python的火车票助手分析的总体结构设计图-程序员宅基地

文章浏览阅读139次。(2)单击主界面“卧铺售票分析”的选项卡,然后输入需要查询的“出发地”与“目的地”,然后单击“查询”按钮将显示如图3所示的卧铺售票分析数据。(1)在主界面“车票查询”选项卡中依次输入,出发地、目的地以及出发时间,然后单击“查询”按钮,将显示如图2所示的车票信息。(3)单击主界面“车票起售时间”的选项卡,然后输入起售车站,再单击“查询”按钮将显示如图4所示的车票起售时间。在PyCharm中运行《火车票分析助手》即可进入如图1所示的系统主界面。图2 车票查询区域的数据显示。图4 显示查询车票起售时间。_基于python的火车票助手分析的总体结构设计图

Nginx重启报错: [error] open() “/usr/local/nginx/logs/nginx.pid“ failed (2: No such file or directory)_nginx: [error] open() "/usr/local/nginx/logs/nginx-程序员宅基地

文章浏览阅读5.3k次,点赞8次,收藏22次。Nginx reload重启报错: [error] open() "/usr/local/nginx/logs/nginx.pid" failed (2: No such file or directory)_nginx: [error] open() "/usr/local/nginx/logs/nginx.pid" failed (2: no such f

科目二经验之谈 10小时必过秘笈_科目二十时十场-程序员宅基地

文章浏览阅读2k次。我认为“学车学车,其实就是学踩离合器”。只要把离合器运用得熟练了,其他的都是小菜一碟。所以,我们要花5小时强化训练踩离合器。踩离合器绝招:不是象教练说的,慢慢松离合器,等车动了就稳住不动,这是不对的。这只会造成车越来越快,正确的方法是慢松离合器到车刚动时,快速往回踩一点(原则是不要把车弄停了),否则车会越来越快的,并在车行进时左脚要源源不断地做踩下、抬起、踩下、抬起这个动作的,否则车不是越_科目二十时十场

推荐文章

热门文章

相关标签