Android 從零編寫一個帶標籤 TagTextView

南塵發表於2019-05-21

最近公司的專案升級到了 9.x,隨之而來的就是一大波的更新,其中有個比較明顯的改變就是很多板塊都出了一個帶標籤的設計圖,如下:
Android 從零編寫一個帶標籤 TagTextView
Android 從零編寫一個帶標籤 TagTextView

怎麼實現

看到這個,大多數小夥伴都能想到這就是一個簡單的圖文混排,不由得會想到鴻洋大佬的圖文並排控制元件 MixtureTextView,或者自己寫一個也不麻煩,只需要利用 shape 背景檔案結合 SpannableString 即可。

確實如此,利用 SpannableString 確實是最方便快捷的方式,但稍不注意這裡可能會踩坑。

private fun convertViewToBitmap(view: View): Bitmap {
    view.isDrawingCacheEnabled = true
    view.measure(View.MeasureSpec.makeMeasureSpec(0, View.MeasureSpec.UNSPECIFIED), View.MeasureSpec.makeMeasureSpec(0, View.MeasureSpec.UNSPECIFIED))
    view.layout(0, 0, view.measuredWidth, view.measuredHeight)
    view.buildDrawingCache()
    val bitmap = view.drawingCache
    view.isDrawingCacheEnabled = false
    view.destroyDrawingCache()
    return bitmap
}

fun setTagText(style: Int, content: String) {
    val view = LayoutInflater.from(context).inflate(R.layout.layout_codoon_tag_textview, null)
    val tagView = view.findViewById<CommonShapeButton>(R.id.tvName)
    val tag = when (style) {
        STYLE_NONE -> {
            ""
        }
        STYLE_CODOON -> {
            tagView.setStrokeColor(R.color.tag_color_codoon.toColorRes())
            tagView.setTextColor(R.color.tag_color_codoon.toColorRes())
            "自營"
        }
        STYLE_JD -> {
            tagView.setStrokeColor(R.color.tag_color_jd.toColorRes())
            tagView.setTextColor(R.color.tag_color_jd.toColorRes())
            "京東"
        }
        STYLE_TM -> {
            tagView.setStrokeColor(R.color.tag_color_tm.toColorRes())
            tagView.setTextColor(R.color.tag_color_tm.toColorRes())
            "天貓"
        }
        STYLE_PDD -> {
            tagView.setStrokeColor(R.color.tag_color_pdd.toColorRes())
            tagView.setTextColor(R.color.tag_color_pdd.toColorRes())
            "拼多多"
        }
        STYLE_TB -> {
            tagView.setStrokeColor(R.color.tag_color_tb.toColorRes())
            tagView.setTextColor(R.color.tag_color_tb.toColorRes())
            "淘寶"
        }
        else -> {
            ""
        }
    }
    val spannableString = SpannableString("$tag$content")
    val bitmap = convertViewToBitmap(view)
    val drawable = BitmapDrawable(resources, bitmap)
    drawable.setBounds(0, 0, tagView.width, tagView.height)
    spannableString.setSpan(CenterImageSpan(drawable), 0, tag.length, Spannable.SPAN_INCLUSIVE_INCLUSIVE)
    text = spannableString
    gravity = Gravity.CENTER_VERTICAL
}

companion object {
    const val STYLE_NONE = 0
    const val STYLE_JD = 1
    const val STYLE_TB = 2
    const val STYLE_CODOON = 3
    const val STYLE_PDD = 4
    const val STYLE_TM = 5
}

xml 檔案的樣式就不必在這裡貼了,很簡單,就是一個帶 shape 背景的 TextView,不過由於 shape 檔案的極難維護性,在我們的專案中統一採用的是自定義 View 來實現這些圓角等效果。

詳細參考作者 blog:Android 專案中 shape 標籤的整理和思考

圓角 shape 等效果不是我們在這裡主要討論的東西,我們來看這個程式碼,思路也是很清晰簡潔:首先利用 LayoutInflater 返回一個 View,然後對這個 View 經過一系列判斷邏輯確認裡面的顯示文案和描邊顏色等處理。然後通過 ViewbuildDrawingCache() 的方法生成一個 Bitmap 供 SpannableString 使用,然後再把 spannableString 設定給 textView 即可。

一些注意點

其中有個細節需要注意的是,利用 LayoutInflater 生成的 View 並沒有經過 measure()layout() 方法的洗禮,所以一定沒對它的 widthheight 等屬性賦值。

所以我們在 buildDrawingCache() 前做了至關重要的兩步操作:

view.measure(View.MeasureSpec.makeMeasureSpec(0, View.MeasureSpec.UNSPECIFIED), View.MeasureSpec.makeMeasureSpec(0, View.MeasureSpec.UNSPECIFIED))
view.layout(0, 0, view.measuredWidth, view.measuredHeight)

buildDrawingCache() 原始碼中我們可以看到,這個方法並不是一定會返回到正確的 Bitmap,在我們的 ViewCacheSize 大小超過了某寫裝置的預設值的時候,可能會返回 null。

系統給我了我們的預設最大的 DrawingCacheSize 為螢幕寬高乘積的 4 倍。

由於我們這裡的 View 是極小的,所以暫時沒有出現返回 null 的情況。

儘管上面的程式碼經過測試,基本上能在大部分機型上滿足需求。但本著被標記 @Deprecated 的過時方法,我們堅決不用的思想,我們需要對生成 Bitmap 的方法進行小範圍改造。

在最新的 SDK 中,我們發現 ViewbuildDrawingCache() 等一系列方法都已經被標記了 @Deprecated

/**
 * <p>Calling this method is equivalent to calling <code>buildDrawingCache(false)</code>.</p>
 *
 * @see #buildDrawingCache(boolean)
 *
 * @deprecated The view drawing cache was largely made obsolete with the introduction of
 * hardware-accelerated rendering in API 11. With hardware-acceleration, intermediate cache
 * layers are largely unnecessary and can easily result in a net loss in performance due to the
 * cost of creating and updating the layer. In the rare cases where caching layers are useful,
 * such as for alpha animations, {@link #setLayerType(int, Paint)} handles this with hardware
 * rendering. For software-rendered snapshots of a small part of the View hierarchy or
 * individual Views it is recommended to create a {@link Canvas} from either a {@link Bitmap} or
 * {@link android.graphics.Picture} and call {@link #draw(Canvas)} on the View. However these
 * software-rendered usages are discouraged and have compatibility issues with hardware-only
 * rendering features such as {@link android.graphics.Bitmap.Config#HARDWARE Config.HARDWARE}
 * bitmaps, real-time shadows, and outline clipping. For screenshots of the UI for feedback
 * reports or unit testing the {@link PixelCopy} API is recommended.
 */
@Deprecated 
public void buildDrawingCache() {
    buildDrawingCache(false);
}       

從官方註釋中我們發現,使用檢視渲染已經過時,硬體加速後中間快取很多程度上都是不必要的,而且很容易導致效能的淨損失。

所以我們採用 Canvas 進行簡單改造一下:

private fun convertViewToBitmap(view: View): Bitmap? {
    view.measure(View.MeasureSpec.makeMeasureSpec(0, View.MeasureSpec.UNSPECIFIED), View.MeasureSpec.makeMeasureSpec(0, View.MeasureSpec.UNSPECIFIED))
    view.layout(0, 0, view.measuredWidth, view.measuredHeight)
    val bitmap = Bitmap.createBitmap(view.measuredWidth, view.measuredHeight, Bitmap.Config.ARGB_4444)
    val canvas = Canvas(bitmap)
    canvas.drawColor(Color.WHITE)
    view.draw(canvas)
    return bitmap
}

突如其來的崩潰

perfect,但很不幸,在上 4.x 某手機上測試的時候,發生了一個空指標崩潰。
Android 從零編寫一個帶標籤 TagTextView
一看日誌,發現我們在執行 view.measure(View.MeasureSpec.makeMeasureSpec(0, View.MeasureSpec.UNSPECIFIED), View.MeasureSpec.makeMeasureSpec(0, View.MeasureSpec.UNSPECIFIED)) 這句程式碼的時候丟擲了系統層原始碼的 bug。

進入原始碼發現在 RelativeLayoutonMeasure() 中有這樣一段程式碼。

if (isWrapContentWidth) {
    // Width already has left padding in it since it was calculated by looking at
    // the right of each child view
    width += mPaddingRight;

    if (mLayoutParams != null && mLayoutParams.width >= 0) {
        width = Math.max(width, mLayoutParams.width);
    }

    width = Math.max(width, getSuggestedMinimumWidth());
    width = resolveSize(width, widthMeasureSpec);
    // ...
    }
}

看起來沒有任何問題,但對比 4.3 的原始碼,發現了一點端倪。

if (mLayoutParams.width >= 0) {
      width = Math.max(width, mLayoutParams.width);
}

原來空指標報的是這個 layoutParams
再看看我們 inflate() 的程式碼。

val view = LayoutInflater.from(context).inflate(R.layout.layout_codoon_tag_textview, null)

對任何一位 Android 開發來講,都是最熟悉的程式碼了,意思很簡單,從 xml 中例項化 View 檢視,但是父檢視為 null,所以從 xml 檔案例項化的 View 檢視沒辦法 attachView 層次樹中,所以導致了 layoutParams 這個引數為 null。
既然找到了原因,那麼解決方案也就非常簡單了。
只需要在 inflate() 後,再設定一下 params 就可以了。

view.layoutParams = ViewGroup.LayoutParams(ViewGroup.LayoutParams.WRAP_CONTENT, ViewGroup.LayoutParams.WRAP_CONTENT)

至此,基本已經實現,主要邏輯程式碼為:

/**
 * 電商專用的 TagTextView
 * 後面可以擴充直接設定顏色和樣式的其他風格
 *
 * Author: nanchen
 * Email: liusl@codoon.com
 * Date: 2019/5/7 10:43
 */
class CodoonTagTextView @JvmOverloads constructor(
        context: Context, attrs: AttributeSet? = null, defStyleAttr: Int = 0
) : AppCompatTextView(context, attrs, defStyleAttr) {

    private var tagTvSize: Float = 0f

    init {
        val array = context.obtainStyledAttributes(attrs, R.styleable.CodoonTagTextView)
        val style = array.getInt(R.styleable.CodoonTagTextView_codoon_tag_style, 0)
        val content = array.getString(R.styleable.CodoonTagTextView_codoon_tag_content)
        tagTvSize = array.getDimension(R.styleable.CodoonTagTextView_codoon_tag_tv_size, 0f)
        content?.apply {
            setTagText(style, this)
        }
        array.recycle()
    }

    private fun convertViewToBitmap(view: View): Bitmap? {
//        view.isDrawingCacheEnabled = true
        view.measure(View.MeasureSpec.makeMeasureSpec(0, View.MeasureSpec.UNSPECIFIED), View.MeasureSpec.makeMeasureSpec(0, View.MeasureSpec.UNSPECIFIED))
        view.layout(0, 0, view.measuredWidth, view.measuredHeight)
//        view.buildDrawingCache()
//        val bitmap = view.drawingCache
//        view.isDrawingCacheEnabled = false
//        view.destroyDrawingCache()
        val bitmap = Bitmap.createBitmap(view.measuredWidth, view.measuredHeight, Bitmap.Config.ARGB_4444)
        val canvas = Canvas(bitmap)
        canvas.drawColor(Color.WHITE)
        view.draw(canvas)
        return bitmap
    }

    fun setTagText(style: Int, content: String) {
        val view = LayoutInflater.from(context).inflate(R.layout.layout_codoon_tag_textview, null)
        view.layoutParams = ViewGroup.LayoutParams(ViewGroup.LayoutParams.WRAP_CONTENT, ViewGroup.LayoutParams.WRAP_CONTENT)
        val tagView = view.findViewById<CommonShapeButton>(R.id.tvName)
        val tag = when (style) {
            STYLE_NONE -> {
                ""
            }
            STYLE_CODOON -> {
                tagView.setStrokeColor(R.color.tag_color_codoon.toColorRes())
                tagView.setTextColor(R.color.tag_color_codoon.toColorRes())
                "自營"
            }
            STYLE_JD -> {
                tagView.setStrokeColor(R.color.tag_color_jd.toColorRes())
                tagView.setTextColor(R.color.tag_color_jd.toColorRes())
                "京東"
            }
            STYLE_TM -> {
                tagView.setStrokeColor(R.color.tag_color_tm.toColorRes())
                tagView.setTextColor(R.color.tag_color_tm.toColorRes())
                "天貓"
            }
            STYLE_PDD -> {
                tagView.setStrokeColor(R.color.tag_color_pdd.toColorRes())
                tagView.setTextColor(R.color.tag_color_pdd.toColorRes())
                "拼多多"
            }
            STYLE_TB -> {
                tagView.setStrokeColor(R.color.tag_color_tb.toColorRes())
                tagView.setTextColor(R.color.tag_color_tb.toColorRes())
                "淘寶"
            }
            else -> {
                ""
            }
        }
        if (tag.isNotEmpty()) {
            tagView.text = tag
            if (tagTvSize != 0f) {
                tagView.textSize = tagTvSize.toDpF()
            }
//            if (tagHeight != 0f) {
//                val params = tagView.layoutParams
//                params.height = tagHeight.toInt()
//                tagView.layoutParams = params
//            }
        }
        val spannableString = SpannableString("$tag$content")
        val bitmap = convertViewToBitmap(view)
        bitmap?.apply {
            val drawable = BitmapDrawable(resources, bitmap)
            drawable.setBounds(0, 0, tagView.width, tagView.height)
            spannableString.setSpan(CenterImageSpan(drawable), 0, tag.length, Spannable.SPAN_INCLUSIVE_INCLUSIVE)
        }
        text = spannableString
        gravity = Gravity.CENTER_VERTICAL
    }

    companion object {
        const val STYLE_NONE = 0    // 不加
        const val STYLE_JD = 1      // 京東
        const val STYLE_TB = 2      // 淘寶
        const val STYLE_CODOON = 3  // 自營
        const val STYLE_PDD = 4     // 拼多多
        const val STYLE_TM = 5      // 天貓
    }
}

相關文章