安卓自定義標(biāo)簽

最近在某安卓開發(fā)QQ群看到這樣一個(gè)需求


RTQV50}OUDR~PKE{V{JLG)J.png

大家推薦用RL或者FL加切圖的方式實(shí)現(xiàn)
為了提高自己的自定義控件水平(其實(shí)是最近比較清閑哈哈),試著做了一下,效果如下


Screenshot_20190109.jpg
Screenshot_20190109-115618.jpg

感覺還行,代碼如下

 /**
     * 線條畫筆
     */
    private val paint = Paint()
    /**
     * 文字畫筆
     */
    private val textPaint = Paint()
    /**
     * 顏色畫筆
     */
    private val colorPaint = Paint()
    private val path = Path()
    /**
     * 標(biāo)簽矩形寬度
     */
    private var rectangleWidth = 0f
    /**
     * 標(biāo)簽凸出部分寬度
     */
    private var triangleWidth = 0f
    private var mHeight = 0f
    /**
     * 文字的padding
     */
    private var tagPaddingHorizontal = 10f
    private var tagPaddingVertical = 10f

    private var tagNum = -1
    private var tagSize = 10f
    private var defaultTag = "標(biāo)簽"
    /**
     * 標(biāo)簽文本和顏色列表
     */
    private val tagList = mutableListOf<String>()
    private val tagColorList = mutableListOf<Int>()
    private var selectTagIndex = 0
    private var selectTagColor = Color.BLUE
    private var tagTextColor = Color.BLACK
    private val textRect = Rect()

    init {
        val typeArray = context.obtainStyledAttributes(attrs, R.styleable.TagView)
        tagNum = typeArray.getInteger(R.styleable.TagView_tagNum, -1)
        tagSize = typeArray.getDimension(R.styleable.TagView_tagSize, context.resources.getDimension(R.dimen.dimen_size_10))
        tagPaddingHorizontal = typeArray.getDimension(R.styleable.TagView_tagPaddingHorizontal, context.resources.getDimension(R.dimen.dimen_size_6))
        tagPaddingVertical = typeArray.getDimension(R.styleable.TagView_tagPaddingVertical, context.resources.getDimension(R.dimen.dimen_size_6))
        selectTagIndex = typeArray.getInteger(R.styleable.TagView_selectTagIndex, 0)
        selectTagColor = typeArray.getColor(R.styleable.TagView_selectTagColor, Color.BLUE)
        tagTextColor = typeArray.getColor(R.styleable.TagView_tagTextColor, Color.BLACK)
        defaultTag = typeArray.getString(R.styleable.TagView_defaultTag) ?: "標(biāo)簽"
        typeArray.recycle()
        paint.apply {
            color = Color.parseColor("#e1e1e1")
            style = Paint.Style.STROKE
            strokeWidth = 4f
        }
        textPaint.apply {
            textSize = tagSize
            color = tagTextColor
            textAlign = Paint.Align.CENTER
        }
        colorPaint.color = selectTagColor
        //以三個(gè)字的長度為例算出標(biāo)簽文本的寬高
        textPaint.getTextBounds("一一一", 0, 3, textRect)
    }

    fun setTagNum(num: Int) {
        tagNum = num
        invalidate()
    }

    fun setTagList(list: List<String>) {
        tagList.clear()
        tagList.addAll(list)
        if (tagList.size < tagNum) {
            for (i in tagNum - tagList.size until tagList.size) {
                tagList.add(defaultTag)
            }
        }
        invalidate()
    }

    fun setColorList(list: List<Int>) {
        tagColorList.clear()
        tagColorList.addAll(list)
        if (tagColorList.size < tagNum) {
            for (i in tagNum - tagColorList.size until tagColorList.size) {
                tagColorList.add(selectTagColor)
            }
        }
        invalidate()
    }

    fun setSelectTag(index: Int) {
        selectTagIndex = index
        if (selectTagIndex < 0 || selectTagIndex >= tagNum)
            selectTagIndex = 0
        invalidate()
    }

    override fun onDraw(canvas: Canvas) {
        //標(biāo)簽數(shù)量為1的時(shí)候單獨(dú)處理,可以不管
        if (tagNum == 1) {
            path.reset()
            path.moveTo(0f + paddingStart, 0f + paddingTop)
            path.lineTo(0f + paddingStart, (measuredHeight - paddingBottom).toFloat())
            path.lineTo(measuredWidth - paddingEnd - (measuredHeight - paddingTop - paddingBottom) / 2f, (measuredHeight - paddingBottom).toFloat())
            path.lineTo((measuredWidth - paddingEnd).toFloat(), (measuredHeight + paddingTop - paddingBottom) / 2f)
            path.lineTo(measuredWidth - paddingEnd - (measuredHeight - paddingTop - paddingBottom) / 2f, 0f + paddingTop)
            path.close()
            canvas.drawPath(path, if (selectTagIndex == 0) colorPaint else paint)
            textPaint.color = if (selectTagIndex == 0) Color.WHITE else tagTextColor
            canvas.drawText(defaultTag, (measuredWidth + paddingStart - paddingEnd - (measuredHeight - paddingTop - paddingBottom) / 2f) / 2f, (measuredHeight + paddingTop - paddingBottom + textRect.bottom - textRect.top) / 2f, textPaint)
        } else
            for (i in 0 until tagNum) {
                path.reset()
                if (i == 0) path.moveTo(0f + paddingStart, 0f + paddingTop)
                else path.moveTo((i - 1) * triangleWidth + i * rectangleWidth + paddingStart, 0f + paddingTop)
                //第一個(gè)標(biāo)簽的左邊是直線,其他都是折線
                if (i == 0) path.rLineTo(0f, mHeight)
                else {
                    path.rLineTo(mHeight / 2f, mHeight / 2f)
                    path.rLineTo(-mHeight / 2f, mHeight / 2f)
                }
                //第一個(gè)標(biāo)簽比其他標(biāo)簽的底邊少一個(gè)凸起的寬度
                if (i == 0) path.rLineTo(rectangleWidth, 0f)
                else path.rLineTo(triangleWidth + rectangleWidth, 0f)
                //最后一個(gè)標(biāo)簽的右邊是直線,其他都是折線
                if (i == tagNum - 1) {
                    path.rLineTo(0f, -mHeight)
                } else {
                    path.rLineTo(mHeight / 2f, -mHeight / 2f)
                    path.rLineTo(-mHeight / 2f, -mHeight / 2f)
                }
                path.close()
                canvas.drawPath(path, if (selectTagIndex == i) colorPaint.apply { color = tagColorList[i] } else paint)
                textPaint.color = if (selectTagIndex == i) Color.WHITE else tagTextColor
                //文字畫在標(biāo)簽矩形范圍中心
                canvas.drawText(tagList[i], paddingStart + (2 * i + 1) * rectangleWidth / 2f + i * triangleWidth, mHeight + paddingTop - tagPaddingVertical, textPaint)
            }
    }

    override fun onMeasure(widthMeasureSpec: Int, heightMeasureSpec: Int) {
        mHeight = textRect.bottom - textRect.top + tagPaddingVertical * 2f
        rectangleWidth = textRect.width() + tagPaddingHorizontal * 2
        triangleWidth = mHeight / 2f
        val width = MeasureSpec.getSize(widthMeasureSpec)
        var num = ((width - paddingStart - paddingEnd) / (rectangleWidth + triangleWidth)).toInt()
        if ((width - paddingStart - paddingEnd) % (rectangleWidth + triangleWidth) >= rectangleWidth) {
            num++
        }
        //如果未設(shè)置標(biāo)簽數(shù)量,按系統(tǒng)分配的寬度算出標(biāo)簽數(shù)量
        if (tagNum == -1)
            tagNum = num
        if (tagNum == 1) {
            setMeasuredDimension((rectangleWidth + triangleWidth + paddingStart + paddingEnd).toInt(), (mHeight + paddingTop + paddingBottom).toInt())
        } else {
            setMeasuredDimension((rectangleWidth * tagNum + triangleWidth * (tagNum - 1) + paddingStart + paddingEnd).toInt(), (mHeight + paddingTop + paddingBottom).toInt())
        }
    }

xml

  <TagView
            android:id="@+id/tag_view"
            android:layout_width="wrap_content"
            android:layout_height="wrap_content"
            app:tagNum="1"
            android:padding="@dimen/dimen_size_10"/>

        <EditText
            android:id="@+id/et"
            android:layout_width="100dp"
            android:layout_height="wrap_content"
            android:layout_below="@+id/tag_view"
            android:inputType="number"/>

        <Button
            android:id="@+id/btn"
            android:layout_width="wrap_content"
            android:layout_height="wrap_content"
            android:text="確定"
            android:layout_below="@+id/et"/>

act

        tagView.apply {
            setTagNum(5)
            setTagList(mutableListOf("未簽到", "已簽到", "未充電", "充電中", "已充電"))
            setColorList(mutableListOf(Color.GREEN, Color.BLUE, Color.YELLOW, Color.RED, Color.BLACK))
        }
        btn.setOnClickListener {
            if (et.text.toString().isNotEmpty())
                tagView.setSelectTag(mBinding.et.text.toString().toInt())
        }

如有問題或不足之處,歡迎批評(píng)指正

?著作權(quán)歸作者所有,轉(zhuǎn)載或內(nèi)容合作請(qǐng)聯(lián)系作者
【社區(qū)內(nèi)容提示】社區(qū)部分內(nèi)容疑似由AI輔助生成,瀏覽時(shí)請(qǐng)結(jié)合常識(shí)與多方信息審慎甄別。
平臺(tái)聲明:文章內(nèi)容(如有圖片或視頻亦包括在內(nèi))由作者上傳并發(fā)布,文章內(nèi)容僅代表作者本人觀點(diǎn),簡書系信息發(fā)布平臺(tái),僅提供信息存儲(chǔ)服務(wù)。

相關(guān)閱讀更多精彩內(nèi)容

友情鏈接更多精彩內(nèi)容