Android 自定義View之隨機數驗證碼(仿寫鴻洋)

語言: CN / TW / HK

前言

本文面向自定義view新手,但是希望你最好有一定的理論知識,或基礎概念,有的地方可能會一筆帶過並不會細講,細講篇幅就太長了。

本文仿寫自鴻洋的自定義View (一),儘管過去了將近快7年之久,我覺得依然有學習價值。

效果

在這裡插入圖片描述

自定義View分類

簡單介紹一下自定義View分類:

  • 組合控制元件,繼承自已有的layout,比如LinearLayout,然後通過LayoutInflater引入佈局,然後處理相關事件,這種方式的好處在於,不需要過度關注view內部的繪製機制,而且擴充套件性也很強。
  • 繼承自現有的系統控制元件,修改或擴充套件某些屬性或方法即可,比如AppCompatTextView
  • 繼承自viewviewgroup,這種相對要複雜一些,因為我們要自己控制繪製流程,但是相對的,也有更大的想象空間。

步驟

先分析一下上圖中的效果:

  • 帶顏色的矩形背景
  • 居中的文字

比較簡單,老手稍微想一下就已經有思路了:

  • 1.自定義屬性
  • 2.新增構造方法
  • 3.在構造裡獲取自定義樣式
  • 4.重寫onDraw計算座標繪製
  • 5.重寫onMeasure測量寬高
  • 6.設定點選事件

先分析效果圖,然後構思,隨後不斷的調整優化。

1.自定義屬性

這一步也不一定非要寫在前面,可能有些人覺得不一定就能事先知道會用到哪些屬性,由於例子比較簡單,暫且放在前面吧,看個人習慣。

  • res/values/ 下建立一個attrs.xml檔案 , 在裡面定義我們的屬性和宣告我們的整個樣式
<?xml version="1.0" encoding="utf-8"?>
<resources>

    <attr name="randomText" format="string"/>
    <attr name="randomTextColor" format="color"/>
    <attr name="randomTextSize" format="dimension"/>

    <declare-styleable name="RandomTextView" >
        <attr name="randomText"/>
        <attr name="randomTextColor"/>
        <attr name="randomTextSize"/>
    </declare-styleable>

</resources>
複製程式碼

format是值該屬性的取值型別: 一共有:string,color,demension,integer,enum,reference,float,boolean,fraction,flag

  • xml佈局中的引用:
    <com.yechaoa.customviews.randomtext.RandomTextView
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:padding="20dp"
        app:randomText="1234"
        app:randomTextColor="@color/colorAccent"
        app:randomTextSize="50sp" />
複製程式碼

注意引入名稱空間

xmlns:app="http://schemas.android.com/apk/res-auto"
複製程式碼

2.新增構造方法

新建一個RandomTextView類,繼承View,並新增3個構造方法

class RandomTextView : View {

    //文字
    private var mRandomText: String

    //文字顏色
    private var mRandomTextColor: Int = 0

    //文字字型大小
    private var mRandomTextSize: Int = 0

    private var paint = Paint()
    private var bounds = Rect()

    //呼叫兩個引數的構造
    constructor(context: Context) : this(context, null)

    //xml預設呼叫兩個引數的構造,再呼叫三個引數的構造,在三個引數構造裡獲取自定義屬性
    constructor(context: Context, attributeSet: AttributeSet?) : this(context, attributeSet, 0)

    constructor(context: Context, attributeSet: AttributeSet?, defStyle: Int) : super(context, attributeSet, defStyle) {
        ...
    }
    ...
}
複製程式碼

這裡要注意的是,所有的構造方法,都指向的是第三個構造方法,前兩個構造的繼承是this,而不是super

第一個構造比如我們可以是new建立的,第二個是xml中預設呼叫的,我們在第三個構造中去獲取自定義屬性。

3.在構造裡獲取自定義樣式

    constructor(context: Context, attributeSet: AttributeSet?, defStyle: Int) : super(context, attributeSet, defStyle) {
        //獲取自定義屬性
        val typedArray = context.theme.obtainStyledAttributes(
            attributeSet,
            R.styleable.RandomTextView,
            defStyle,
            0
        )

        mRandomText = typedArray.getString(R.styleable.RandomTextView_randomText).toString()
        mRandomTextColor = typedArray.getColor(R.styleable.RandomTextView_randomTextColor, Color.BLACK)//預設黑色
        mRandomTextSize = typedArray.getDimensionPixelSize(
            R.styleable.RandomTextView_randomTextSize,
            TypedValue.applyDimension( TypedValue.COMPLEX_UNIT_SP, 16F, resources.displayMetrics ).toInt()
        )

        //獲取完回收
        typedArray.recycle()

        paint.textSize = mRandomTextSize.toFloat()

        //返回文字邊界,即包含文字的最小矩形,沒有所謂“留白”,返回比measureText()更精確的text寬高,資料儲存在bounds裡
        paint.getTextBounds(mRandomText, 0, mRandomText.length, bounds)
    }
複製程式碼

通過obtainStyledAttributes獲取自定義屬性,返回一個TypedArray,這裡用到了我們在attrs.xml檔案中宣告的樣式(R.styleable.RandomTextView),返回的TypedArray即包含了這裡面的屬性。

拿到自定義view屬性集合,然後賦值,賦值之後就可以用paint去畫了。

然後用到了paint的getTextBounds方法:

paint.getTextBounds(mRandomText, 0, mRandomText.length, bounds)
複製程式碼

簡單理解就是,把文字放在一個矩形裡,通過矩形的寬高即可知道文字的寬高,所以寬高會儲存在bounds裡,bounds是一個矩形Rect,為什麼要這麼做呢,因為後面我們要計算文字居中的時候會用到。

ok,接下來開始畫布局。

4.重寫onDraw計算座標繪製

    @SuppressLint("DrawAllocation")
    override fun onDraw(canvas: Canvas?) {
        super.onDraw(canvas)

        /**
         * 自定義View時,需要我們自己在onDraw中處理padding,否則是不生效的
         * 自定義ViewGroup時,子view的padding放在onMeasure中處理
         */

        /**
         * 矩形背景
         */
        paint.color = Color.YELLOW
        //計算座標,因為原點是在文字的左下角,左邊要是延伸出去就還要往左邊去,所以是減,右邊和下邊是正,所以是加
        canvas?.drawRect(
            (0 - paddingLeft).toFloat(),
            (0 - paddingTop).toFloat(),
            (measuredWidth + paddingRight).toFloat(),
            (measuredHeight + paddingBottom).toFloat(),
            paint
        )

        /**
         * 文字
         */
        paint.color = mRandomTextColor
        //注意這裡的座標xy不是左上角,而是左下角,所以高度是相加的,在自定義view中,座標軸右下為正
        //getWidth 等於 measuredWidth
        canvas?.drawText(
            mRandomText,
            (width / 2 - bounds.width() / 2).toFloat(),
            (height / 2 + bounds.height() / 2).toFloat(),
            paint
        )
    }
複製程式碼

上面的程式碼就是在onDraw裡面顯示繪製了一個YELLOW顏色的矩形背景,然後繪製了一個自定義屬性顏色的居中的文字。

這裡要注意我們計算位置時的座標,在自定義view中,原點是view的左上角,而在數學座標系中,原點(0,0)是在中間的,二者是有區別的。

其次,假如xml佈局中有padding,或者預判會使用到padding,在重寫onDraw的時候也要把padding的資料加上,否則padding是不生效的。如果是繼承ViewGroup時,子view的padding放在onMeasure中處理。

來看此時的效果:

在這裡插入圖片描述

此時是不是有疑惑,xml裡面的寬高明明是wrap_content,為什麼會充滿父佈局呢?

這就涉及到onMeasure的知識點了,往下看。

5.重寫onMeasure測量寬高

我們在xml設定view寬高有3種方式:

  • match_parent
  • wrap_content
  • 具體資料,比如100dp

onMeasureMeasureSpecmode也有3種模式:

  • EXACTLY:一般是設定了明確的值或者是MATCH_PARENT
  • AT_MOST:表示子佈局限制在一個最大值內,一般為WARP_CONTENT
  • UNSPECIFIED:表示子佈局想要多大就多大,很少使用

由於我們xml用的是wrap_content,也就是對應AT_MOST,所以效果就是會佔滿父佈局中的可用空間,而父佈局是填充螢幕,所以我們自定義的view也會佔滿全屏。

而我們實際想要的效果是view包裹自己,而不是鋪滿全屏,所以我們需要在onMeasure中進行處理

    override fun onMeasure(widthMeasureSpec: Int, heightMeasureSpec: Int) {
        super.onMeasure(widthMeasureSpec, heightMeasureSpec)

        /**
         * EXACTLY:一般是設定了明確的值或者是MATCH_PARENT
         * AT_MOST:表示子佈局限制在一個最大值內,一般為WARP_CONTENT
         * UNSPECIFIED:表示子佈局想要多大就多大,很少使用
         */
        val widthMode = MeasureSpec.getMode(widthMeasureSpec)
        val widthSize = MeasureSpec.getSize(widthMeasureSpec)

        val heightMode = MeasureSpec.getMode(heightMeasureSpec)
        val heightSize = MeasureSpec.getSize(heightMeasureSpec)

        var width = 0
        var height = 0

        //如果指定了寬度,或不限制寬度,用可用寬度即可,如果是WARP_CONTENT,則用文字寬度,再加上左右padding
        when (widthMode) {
            MeasureSpec.UNSPECIFIED,
            MeasureSpec.EXACTLY -> {
                width = widthSize + paddingLeft + paddingRight
            }
            MeasureSpec.AT_MOST -> {
                width = bounds.width() + paddingLeft + paddingRight
            }
        }

        //如果指定了高度,或不限制高度,用可用高度即可,如果是WARP_CONTENT,則用文字高度,再加上上下padding
        when (heightMode) {
            MeasureSpec.UNSPECIFIED,
            MeasureSpec.EXACTLY -> {
                height = heightSize + paddingTop + paddingBottom
            }
            MeasureSpec.AT_MOST -> {
                height = bounds.height() + paddingTop + paddingBottom
            }
        }

        //儲存測量的寬高
        setMeasuredDimension(width, height)
    }
複製程式碼

上面的程式碼呢,主要做了兩件事:

  • 獲取view寬高的模式
  • 針對不同的模式,對寬高進行重新測量

最後別忘記呼叫setMeasuredDimension儲存新測量的寬高,否則沒用哦。

此時再看效果就是效果圖中的樣子了。

6.設定點選事件

ok,到這,view已經繪製完成了,但是還沒有事件,我們在構造中加一個點選事件

    constructor(context: Context, attributeSet: AttributeSet?, defStyle: Int) : super(context, attributeSet, defStyle) {
        ...
        /**
         * 新增點選事件
         */
        this.setOnClickListener {
            mRandomText = randomText()
            //更新
            postInvalidate()
        }
    }
複製程式碼

randomText方法:

    /**
     * 根據文字長度 隨意數字
     */
    private fun randomText(): String {
        val list = mutableListOf<Int>()
        for (index in mRandomText.indices) {
            list.add(Random.nextInt(10))
        }
        val stringBuffer = StringBuffer()
        for (i in list) {
            stringBuffer.append("" + i)
        }
        return stringBuffer.toString()
    }

複製程式碼

觸發事件之後,文字更新,然後view重繪更新頁面即可。

關於資料獲取,也就是變化後的數字,可以寫個onTextChanged介面,也可以寫個開放方法獲取。

總結

其實看效果的話,還不如TextView來的簡單,而且TextView也可以輕鬆的實現效果圖中的效果。

所以本文的重點並不是實現效果,而是學習理解自定義View以及其繪製流程

理論看的再多也需要實踐才行,不如跟著敲兩遍,理解消化一下。

註釋還是非常詳細的,甚至有點囉嗦。。

如果對你有一點幫助,點個讚唄 ^ _ ^

Github

github.com/yechaoa/Cus…

參考