最近公司的項目升級到了 9.x,隨之而來的就是一大波的更新,其中有個比較明顯的改變就是不少板塊都出了一個帶標籤的設計圖,以下:
java
看到這個,大多數小夥伴都能想到這就是一個簡單的圖文混排,不禁得會想到鴻洋大佬的圖文並排控件 MixtureTextView,或者本身寫一個也不麻煩,只須要利用 shape 背景文件結合 SpannableString
便可。android
確實如此,利用 SpannableString
確實是最方便快捷的方式,但稍不注意這裏可能會踩坑。git
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 來實現這些圓角等效果。github
詳細參考做者 blog:Android 項目中 shape 標籤的整理和思考canvas
圓角 shape 等效果不是咱們在這裏主要討論的東西,咱們來看這個代碼,思路也是很清晰簡潔:首先利用 LayoutInflater
返回一個 View
,而後對這個 View
通過一系列判斷邏輯確認裏面的顯示文案和描邊顏色等處理。而後經過 View
的 buildDrawingCache()
的方法生成一個 Bitmap 供 SpannableString
使用,而後再把 spannableString
設置給 textView
便可。緩存
其中有個細節須要注意的是,利用 LayoutInflater
生成的 View
並無通過 measure()
和 layout()
方法的洗禮,因此必定沒對它的 width
和 height
等屬性賦值。app
因此咱們在 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
,在咱們的 View
的 CacheSize
大小超過了某寫設備的默認值的時候,可能會返回 null。測試
系統給我了咱們的默認最大的
DrawingCacheSize
爲屏幕寬高乘積的 4 倍。ui
因爲咱們這裏的 View 是極小的,因此暫時沒有出現返回 null 的狀況。
儘管上面的代碼通過測試,基本上能在大部分機型上知足需求。但本着被標記 @Deprecated
的過期方法,咱們堅定不用的思想,咱們須要對生成 Bitmap
的方法進行小範圍改造。
在最新的 SDK 中,咱們發現 View
的 buildDrawingCache()
等一系列方法都已經被標記了 @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 某手機上測試的時候,發生了一個空指針崩潰。
一看日誌,發現咱們在執行 view.measure(View.MeasureSpec.makeMeasureSpec(0, View.MeasureSpec.UNSPECIFIED), View.MeasureSpec.makeMeasureSpec(0, View.MeasureSpec.UNSPECIFIED))
這句代碼的時候拋出了系統層源碼的 bug。
進入源碼發如今 RelativeLayout
的 onMeasure()
中有這樣一段代碼。
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
視圖沒辦法 attach
到 View
層次樹中,因此致使了 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 // 天貓 } }