Search code examples
androidandroid-layoutandroid-custom-view

Get space between text and bound of TextView


I'm trying to get the distance between the text and the left side of a TextView. It uses the property android:gravity="center".

enter image description here

I want to get the distance of the red bar (this red bar is not a part of the layout) to center the blue button. What should I do? The dark area represents the bounds of the TextView.

I don't want to use a compoundDrawable because this view will change the color of the button randomly.

The code of the view (written in Kotlin):

class BallTextView: TextView {

  private lateinit var ballPaint : Paint
  private var ballRadius : Float = 10f
  private var ballColor : Int = Color.BLACK

  constructor(ctx: Context, attrs: AttributeSet) : super(ctx, attrs) {
    initializeAttributes(attrs)
    configBall()
  }

  override fun onDraw(canvas: Canvas) {
    canvas.drawCircle(ballRadius, height.toFloat()/2, ballRadius, ballPaint)
    super.onDraw(canvas)
  }

  fun configBall() {
    ballPaint = Paint()
    ballPaint.isAntiAlias = true
    ballPaint.color = ballColor
  }

  fun initializeAttributes(attrs: AttributeSet) {
    val attributes = context.obtainStyledAttributes(attrs, R.styleable.ball_textview)
    ballRadius = TypedValue.applyDimension(TypedValue.COMPLEX_UNIT_DIP,
        attributes.getFloat(R.styleable.ball_textview_ball_radius, ballRadius),
        context.resources.displayMetrics)
    ballColor = attributes.getColor(R.styleable.ball_textview_ball_color, ballColor)
  }

}

Thanks.


Solution

  • The TextView#getLineBounds(int, Rect) method is what you want.

    The first parameter is the zero-based line number, and the second is a Rect object that will hold the bounds values of the given line after the call. The left field of the Rect will have the horizontal inset of the line, which you can use with the radius of your drawn circle to figure its center's x coordinate.