android自定义控件类型,Android自定义控件 | 小红点的三种实现(上)

2023-12-17 15:59

本文主要是介绍android自定义控件类型,Android自定义控件 | 小红点的三种实现(上),希望对大家解决编程问题提供一定的参考价值,需要的开发者们随着小编来一起学习吧!

小红点用于通知未读消息,在应用中到处可见。本文将介绍三种实现方案。分别是:多控件方案、单控件绘制方案、容器控件绘制方案。不知道你会更偏向哪种方案?

Demo 使用 Kotlin 编写,Kotlin系列教程可以点击这里

多控件方案

多控件最容易想到的方案:TextView作为主体控件,View作为附属小红点控件相互叠加。效果如下:

54965003a9476e04f802bcb04c58febc.png

布局文件如下:

android:layout_width="wrap_content"

android:layout_height="wrap_content">

android:id="@+id/tvMsg"

android:layout_width="match_parent"

android:layout_height="wrap_content"

android:text="消息"

android:textSize="20sp"/>

android:layout_width="6dp"

android:layout_height="6dp"

android:background="@drawable/red_shape"

app:layout_constraintEnd_toEndOf="@id/tvMsg"

app:layout_constraintTop_toTopOf="@id/tvMsg" />

复制代码

其中red_shape是一个红色圆形shape资源文件,代码如下:

android:shape="oval">

android:height="20dp"/>

复制代码

若要显示未读消息数,可以将View换成TextView。

这个方案最大的优点是简单直观,如果项目赶,没有太多时间深思,用这交差也不错。

但它的缺点是增加了控件的数量,如果一个页面中有3个小红点,就增加3个控件。

有什么办法可以两个控件合成一个控件?

单控件绘制方案

是不是可以自定义一个TextView,在右上角绘制一个红圈。

绘制分为两步:

绘制红色背景

绘制消息数

绘制背景

Canvas有现成的 API 绘制圆圈:

public class Canvas extends BaseCanvas {

/**

* Draw the specified circle using the specified paint. If radius is <= 0, then nothing will be

* drawn. The circle will be filled or framed based on the Style in the paint.

*

* @param cx The x-coordinate of the center of the cirle to be drawn

* @param cy The y-coordinate of the center of the cirle to be drawn

* @param radius The radius of the cirle to be drawn

* @param paint The paint used to draw the circle

*/

public void drawCircle(float cx, float cy, float radius, @NonNull Paint paint) {

super.drawCircle(cx, cy, radius, paint);

}

}

复制代码

只需计算出圆心坐标和半径,然后在onDraw()中调用该 API 即可绘制。

背景的圆心应该是消息数的中心点,背景的半径依赖于消息数的长短,比如,9 条未读消息就比 999 条的背景要小一圈。

绘制消息数

先绘制背景,再绘制消息数,是为了不让其被背景挡住。

Canvas有现成的 API 绘制文字:

public class Canvas extends BaseCanvas {

/**

* Draw the text, with origin at (x,y), using the specified paint. The origin is interpreted

* based on the Align setting in the paint.

*

* @param text The text to be drawn

* @param x The x-coordinate of the origin of the text being drawn

* @param y The y-coordinate of the baseline of the text being drawn

* @param paint The paint used for the text (e.g. color, size, style)

*/

public void drawText(@NonNull String text, float x, float y, @NonNull Paint paint) {

super.drawText(text, x, y, paint);

}

}

复制代码

其中第三个参数y是指文字基线的纵坐标,如下图所示:

6a87c520231465cd06ac320b8eef1837.png

画文字的关键是求出基线在父控件中的纵坐标,当前 case 的示意图如下:

af6f3aae64f02bc1e02e536a94c5b62b.png

圆圈代表小红点的背景,紫线是圆圈的直径,也是文字的中轴线。小红点绘制在控件的右上角,圆圈的上边和右边分别贴住控件的上边和右边,所以圆圈顶部切线的纵坐标为 0。问题变成已知半径raduis,top,bottom,求 baseLine 纵坐标?(top是负值,bottom为正值)

分解一下计算步骤:

raduis:紫线的纵坐标

(bottom - top) / 2:文字区域总高度的一半

radius + (bottom - top) / 2:文字底部的纵坐标

文字底部的纵坐标减掉 bottom 的值就是基线的纵坐标:

baseline = radius + (bottom - top) / 2 - bottom

然后只要在自定义控件的onDraw()中先绘制背景再绘制消息数即可,自定义控件完整代码如下:

//'自定义TextView'

open class TagTextView @JvmOverloads constructor(context: Context, attrs: AttributeSet? = null, defStyleAttr: Int = 0) : AppCompatTextView(context, attrs, defStyleAttr) {

//'消息数字体大小'

var tagTextSize: Float = 0F

set(value) {

field = value

textPaint.textSize = value

}

//'消息数字体颜色'

var tagTextColor: Int = Color.parseColor("#FFFFFF")

set(value) {

field = value

textPaint.color = value

}

//'背景色'

var tagBgColor: Int = Color.parseColor("#FFFF5183")

set(value) {

field = value

bgPaint.color = value

}

//'消息数字体'

var tagTextTypeFace: Typeface? = null

//'消息数'

var tagText: String? = null

//'背景和消息数的间距'

var tagTextPaddingTop: Float = 5f

var tagTextPaddingBottom: Float = 5f

var tagTextPaddingStart: Float = 5f

var tagTextPaddingEnd: Float = 5f

//'消息数字体区域'

private var textRect: Rect = Rect()

//'消息数画笔'

private var textPaint: Paint = Paint()

//'背景画笔'

private var bgPaint: Paint = Paint()

init {

//'构建消息数画笔'

textPaint.apply {

color = tagTextColor

textSize = tagTextSize

isAntiAlias = true

textAlign = Paint.Align.CENTER

style = Paint.Style.FILL

tagTextTypeFace?.let { typeface = tagTextTypeFace }

}

//'构建背景画笔'

bgPaint.apply {

isAntiAlias = true

style = Paint.Style.FILL

color = tagBgColor

}

}

override fun onDraw(canvas: Canvas?) {

super.onDraw(canvas)

//'只有当消息数不为空时才绘制小红点'

tagText?.takeIf { it.isNotEmpty() }?.let { text ->

textPaint.apply {

//'1.获取消息数区域大小'

getTextBounds(text, 0, text.length, textRect)

fontMetricsInt.let {

//'背景宽=消息数区域宽+边距'

val bgWidth = (textRect.right - textRect.left) + tagTextPaddingStart + tagTextPaddingEnd

//'背景高=消息数区域高+边距'

val bgHeight = tagTextPaddingBottom + tagTextPaddingTop + it.bottom - it.top

//'取宽高中的较大值作为半径'

val radius = if (bgWidth > bgHeight) bgWidth / 2 else bgHeight / 2

val centerX = width - radius

val centerY = radius

//'2.绘制背景'

canvas?.drawCircle(centerX, centerY, radius, bgPaint)

//'3.绘制基线'

val baseline = radius + (it.bottom - it.top) / 2 - it.bottom

canvas?.drawText(text, width - radius, baseline, textPaint)

}

}

}

}

}

复制代码

然后就能像这样使用自定义控件:

在布局文件中声明

xmlns:app="http://schemas.android.com/apk/res-auto"

android:layout_width="match_parent"

android:layout_height="match_parent">

android:id="@+id/ttv"

android:layout_width="wrap_content"

android:layout_height="wrap_content"

android:padding="8dp"

android:text="bug"/>

复制代码在 Activity 中引用并设置参数:

class TagTextViewActivity:AppCompatActivity() {

override fun onCreate(savedInstanceState: Bundle?) {

super.onCreate(savedInstanceState)

setContentView(R.layout.tag_textview_activity)

ttv.tagText = "+99"

ttv.tagTextSize = dip(8F)

ttv.tagTextColor = Color.YELLOW

}

}

复制代码

把小红点的显示细节隐藏在一个自定义View中,这样布局文件和业务层代码会更加简洁清晰。

但这个方案也有以下缺点:

控件类型绑定:若当前界面分别有一个TextView、ImageView和Button需要显示小红点,那就需要分别构建三种类型的自定义View。

控件需留 padding:小红点是控件的一部分,为了不让小红点与控件本体内容重叠,控件需给小红点留有 padding,即控件占用空间会变大,在布局文件中可能引起连锁反应,使得其他控件位置也需要跟着微调。

于是乎就有了第三种方案~~

容器控件绘制方案

第三种方案较前两种略复杂,限于篇幅就留到下一篇接着讲。

这篇关于android自定义控件类型,Android自定义控件 | 小红点的三种实现(上)的文章就介绍到这儿,希望我们推荐的文章对编程师们有所帮助!



http://www.chinasem.cn/article/504954

相关文章

C++中unordered_set哈希集合的实现

《C++中unordered_set哈希集合的实现》std::unordered_set是C++标准库中的无序关联容器,基于哈希表实现,具有元素唯一性和无序性特点,本文就来详细的介绍一下unorder... 目录一、概述二、头文件与命名空间三、常用方法与示例1. 构造与析构2. 迭代器与遍历3. 容量相关4

C++中悬垂引用(Dangling Reference) 的实现

《C++中悬垂引用(DanglingReference)的实现》C++中的悬垂引用指引用绑定的对象被销毁后引用仍存在的情况,会导致访问无效内存,下面就来详细的介绍一下产生的原因以及如何避免,感兴趣... 目录悬垂引用的产生原因1. 引用绑定到局部变量,变量超出作用域后销毁2. 引用绑定到动态分配的对象,对象

SpringBoot基于注解实现数据库字段回填的完整方案

《SpringBoot基于注解实现数据库字段回填的完整方案》这篇文章主要为大家详细介绍了SpringBoot如何基于注解实现数据库字段回填的相关方法,文中的示例代码讲解详细,感兴趣的小伙伴可以了解... 目录数据库表pom.XMLRelationFieldRelationFieldMapping基础的一些代

Java HashMap的底层实现原理深度解析

《JavaHashMap的底层实现原理深度解析》HashMap基于数组+链表+红黑树结构,通过哈希算法和扩容机制优化性能,负载因子与树化阈值平衡效率,是Java开发必备的高效数据结构,本文给大家介绍... 目录一、概述:HashMap的宏观结构二、核心数据结构解析1. 数组(桶数组)2. 链表节点(Node

Java AOP面向切面编程的概念和实现方式

《JavaAOP面向切面编程的概念和实现方式》AOP是面向切面编程,通过动态代理将横切关注点(如日志、事务)与核心业务逻辑分离,提升代码复用性和可维护性,本文给大家介绍JavaAOP面向切面编程的概... 目录一、AOP 是什么?二、AOP 的核心概念与实现方式核心概念实现方式三、Spring AOP 的关

Python实现字典转字符串的五种方法

《Python实现字典转字符串的五种方法》本文介绍了在Python中如何将字典数据结构转换为字符串格式的多种方法,首先可以通过内置的str()函数进行简单转换;其次利用ison.dumps()函数能够... 目录1、使用json模块的dumps方法:2、使用str方法:3、使用循环和字符串拼接:4、使用字符

Linux下利用select实现串口数据读取过程

《Linux下利用select实现串口数据读取过程》文章介绍Linux中使用select、poll或epoll实现串口数据读取,通过I/O多路复用机制在数据到达时触发读取,避免持续轮询,示例代码展示设... 目录示例代码(使用select实现)代码解释总结在 linux 系统里,我们可以借助 select、

Linux挂载linux/Windows共享目录实现方式

《Linux挂载linux/Windows共享目录实现方式》:本文主要介绍Linux挂载linux/Windows共享目录实现方式,具有很好的参考价值,希望对大家有所帮助,如有错误或未考虑完全的地... 目录文件共享协议linux环境作为服务端(NFS)在服务器端安装 NFS创建要共享的目录修改 NFS 配

通过React实现页面的无限滚动效果

《通过React实现页面的无限滚动效果》今天我们来聊聊无限滚动这个现代Web开发中不可或缺的技术,无论你是刷微博、逛知乎还是看脚本,无限滚动都已经渗透到我们日常的浏览体验中,那么,如何优雅地实现它呢?... 目录1. 早期的解决方案2. 交叉观察者:IntersectionObserver2.1 Inter

Spring Gateway动态路由实现方案

《SpringGateway动态路由实现方案》本文主要介绍了SpringGateway动态路由实现方案,文中通过示例代码介绍的非常详细,对大家的学习或者工作具有一定的参考学习价值,需要的朋友们下面随... 目录前沿何为路由RouteDefinitionRouteLocator工作流程动态路由实现尾巴前沿S