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

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

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

这是自定义控件系列教程的第五篇,系列文章目录如下:

  1. Android自定义控件 | View绘制原理(画多大?)
  2. Android自定义控件 | View绘制原理(画在哪?)
  3. Android自定义控件 | View绘制原理(画什么?)
  4. Android自定义控件 | 源码里有宝藏之自动换行控件
  5. Android自定义控件 | 小红点的三种实现(上)
  6. Android自定义控件 | 小红点的三种实现(下)
  7. Android自定义控件 | 小红点的三种实现(终结)

多控件方案

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

image

布局文件如下:

<androidx.constraintlayout.widget.ConstraintLayout
    android:layout_width="wrap_content"
    android:layout_height="wrap_content">
    <TextView
        android:id="@+id/tvMsg"
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:text="消息"
        android:textSize="20sp"/>

    <View
        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" />
</androidx.constraintlayout.widget.ConstraintLayout>

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

<shape xmlns:android="http://schemas.android.com/apk/res/android"
    android:shape="oval">
    
    <size android:width="20dp"
        android:height="20dp"/>
        
    <solid android:color="#ff0000"/>
</shape>

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

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

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

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

单控件绘制方案

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

绘制分为两步:

  1. 绘制红色背景
  2. 绘制消息数

绘制背景

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是指文字基线的纵坐标,如下图所示:

image

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

image

圆圈代表小红点的背景,紫线是圆圈的直径,也是文字的中轴线。小红点绘制在控件的右上角,圆圈的上边和右边分别贴住控件的上边和右边,所以圆圈顶部切线的纵坐标为 0。问题变成已知半径raduistopbottom,求 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)
                }
            }
        }
    }
}

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

  1. 在布局文件中声明
<?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"
    android:layout_width="match_parent"
    android:layout_height="match_parent">

    <test.taylor.com.taylorcode.ui.custom_view.tag_view.TagTextView
        android:id="@+id/ttv"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:padding="8dp"
        android:text="bug"/>

</androidx.constraintlayout.widget.ConstraintLayout>
  1. 在 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中,这样布局文件和业务层代码会更加简洁清晰。

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

  1. 控件类型绑定:若当前界面分别有一个TextViewImageViewButton需要显示小红点,那就需要分别构建三种类型的自定义View。
  2. 控件需留 padding:小红点是控件的一部分,为了不让小红点与控件本体内容重叠,控件需给小红点留有 padding,即控件占用空间会变大,在布局文件中可能引起连锁反应,使得其他控件位置也需要跟着微调。

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

容器控件绘制方案

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

©著作权归作者所有,转载或内容合作请联系作者
  • 序言:七十年代末,一起剥皮案震惊了整个滨河市,随后出现的几起案子,更是在滨河造成了极大的恐慌,老刑警刘岩,带你破解...
    沈念sama阅读 194,319评论 5 459
  • 序言:滨河连续发生了三起死亡事件,死亡现场离奇诡异,居然都是意外死亡,警方通过查阅死者的电脑和手机,发现死者居然都...
    沈念sama阅读 81,801评论 2 371
  • 文/潘晓璐 我一进店门,熙熙楼的掌柜王于贵愁眉苦脸地迎上来,“玉大人,你说我怎么就摊上这事。” “怎么了?”我有些...
    开封第一讲书人阅读 141,567评论 0 319
  • 文/不坏的土叔 我叫张陵,是天一观的道长。 经常有香客问我,道长,这世上最难降的妖魔是什么? 我笑而不...
    开封第一讲书人阅读 52,156评论 1 263
  • 正文 为了忘掉前任,我火速办了婚礼,结果婚礼上,老公的妹妹穿的比我还像新娘。我一直安慰自己,他们只是感情好,可当我...
    茶点故事阅读 61,019评论 4 355
  • 文/花漫 我一把揭开白布。 她就那样静静地躺着,像睡着了一般。 火红的嫁衣衬着肌肤如雪。 梳的纹丝不乱的头发上,一...
    开封第一讲书人阅读 46,090评论 1 272
  • 那天,我揣着相机与录音,去河边找鬼。 笑死,一个胖子当着我的面吹牛,可吹牛的内容都是我干的。 我是一名探鬼主播,决...
    沈念sama阅读 36,500评论 3 381
  • 文/苍兰香墨 我猛地睁开眼,长吁一口气:“原来是场噩梦啊……” “哼!你这毒妇竟也来了?” 一声冷哼从身侧响起,我...
    开封第一讲书人阅读 35,192评论 0 253
  • 序言:老挝万荣一对情侣失踪,失踪者是张志新(化名)和其女友刘颖,没想到半个月后,有当地人在树林里发现了一具尸体,经...
    沈念sama阅读 39,474评论 1 290
  • 正文 独居荒郊野岭守林人离奇死亡,尸身上长有42处带血的脓包…… 初始之章·张勋 以下内容为张勋视角 年9月15日...
    茶点故事阅读 34,566评论 2 309
  • 正文 我和宋清朗相恋三年,在试婚纱的时候发现自己被绿了。 大学时的朋友给我发了我未婚夫和他白月光在一起吃饭的照片。...
    茶点故事阅读 36,338评论 1 326
  • 序言:一个原本活蹦乱跳的男人离奇死亡,死状恐怖,灵堂内的尸体忽然破棺而出,到底是诈尸还是另有隐情,我是刑警宁泽,带...
    沈念sama阅读 32,212评论 3 312
  • 正文 年R本政府宣布,位于F岛的核电站,受9级特大地震影响,放射性物质发生泄漏。R本人自食恶果不足惜,却给世界环境...
    茶点故事阅读 37,572评论 3 298
  • 文/蒙蒙 一、第九天 我趴在偏房一处隐蔽的房顶上张望。 院中可真热闹,春花似锦、人声如沸。这庄子的主人今日做“春日...
    开封第一讲书人阅读 28,890评论 0 17
  • 文/苍兰香墨 我抬头看了看天上的太阳。三九已至,却和暖如春,着一层夹袄步出监牢的瞬间,已是汗流浃背。 一阵脚步声响...
    开封第一讲书人阅读 30,169评论 1 250
  • 我被黑心中介骗来泰国打工, 没想到刚下飞机就差点儿被人妖公主榨干…… 1. 我叫王不留,地道东北人。 一个月前我还...
    沈念sama阅读 41,478评论 2 341
  • 正文 我出身青楼,却偏偏与公主长得像,于是被迫代替她去往敌国和亲。 传闻我的和亲对象是个残疾皇子,可洞房花烛夜当晚...
    茶点故事阅读 40,661评论 2 335

推荐阅读更多精彩内容