1 /* 2 * Copyright (C) 2018 The Android Open Source Project 3 * 4 * Licensed under the Apache License, Version 2.0 (the "License"); 5 * you may not use this file except in compliance with the License. 6 * You may obtain a copy of the License at 7 * 8 * http://www.apache.org/licenses/LICENSE-2.0 9 * 10 * Unless required by applicable law or agreed to in writing, software 11 * distributed under the License is distributed on an "AS IS" BASIS, 12 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. 13 * See the License for the specific language governing permissions and 14 * limitations under the License. 15 */ 16 package com.android.example.text.styling.roundedbg 17 18 import android.content.Context 19 import android.graphics.Canvas 20 import android.text.Spanned 21 import android.util.AttributeSet 22 import androidx.appcompat.widget.AppCompatTextView 23 import androidx.core.graphics.withTranslation 24 25 /** 26 * A TextView that can draw rounded background to the portions of the text. See 27 * [TextRoundedBgHelper] for more information. 28 * 29 * See [TextRoundedBgAttributeReader] for supported attributes. 30 */ 31 class RoundedBgTextView : AppCompatTextView { 32 33 private val textRoundedBgHelper: TextRoundedBgHelper 34 35 @JvmOverloads 36 constructor( 37 context: Context, 38 attrs: AttributeSet? = null, 39 defStyleAttr: Int = android.R.attr.textViewStyle 40 ) : super(context, attrs, defStyleAttr) { 41 val attributeReader = TextRoundedBgAttributeReader(context, attrs) 42 textRoundedBgHelper = TextRoundedBgHelper( 43 horizontalPadding = attributeReader.horizontalPadding, 44 verticalPadding = attributeReader.verticalPadding, 45 drawable = attributeReader.drawable, 46 drawableLeft = attributeReader.drawableLeft, 47 drawableMid = attributeReader.drawableMid, 48 drawableRight = attributeReader.drawableRight 49 ) 50 } 51 onDrawnull52 override fun onDraw(canvas: Canvas) { 53 // need to draw bg first so that text can be on top during super.onDraw() 54 if (text is Spanned && layout != null) { 55 canvas.withTranslation(totalPaddingLeft.toFloat(), totalPaddingTop.toFloat()) { 56 textRoundedBgHelper.draw(canvas, text as Spanned, layout) 57 } 58 } 59 super.onDraw(canvas) 60 } 61 }