Skip to content

Instantly share code, notes, and snippets.

@isfaaghyth
Created March 18, 2021 02:55
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save isfaaghyth/400078b7cd6d9e9e4ded05bf7e0b214f to your computer and use it in GitHub Desktop.
Save isfaaghyth/400078b7cd6d9e9e4ded05bf7e0b214f to your computer and use it in GitHub Desktop.
import android.content.Context
import android.graphics.Canvas
import android.util.AttributeSet
import androidx.appcompat.widget.AppCompatEditText
class CustomEditTextView: AppCompatEditText {
private var padding = -1f
private var prefix = ""
constructor(context: Context) : super(context) {
init(context, null)
}
constructor(context: Context, attrs: AttributeSet?) : super(context, attrs) {
init(context, attrs)
}
constructor(context: Context, attrs: AttributeSet?, defStyleAttr: Int) : super(context, attrs, defStyleAttr) {
init(context, attrs)
}
fun init(context: Context, attributeSet: AttributeSet?) {
attributeSet?.let {
val typedArray = context.obtainStyledAttributes(attributeSet, R.styleable.EditText)
prefix = typedArray.getString(R.styleable.EditText_prefix)
typedArray.recycle()
}
}
fun prefix(prefix: String) = apply {
this.prefix = prefix
invalidate()
}
override fun onDraw(canvas: Canvas?) {
super.onDraw(canvas)
if (prefix.isNotEmpty()) {
prefixSet()
canvas?.drawText(prefix, padding, getLineBounds(0, null).toFloat(), paint)
}
}
private fun prefixSet() {
if (padding == -1f) {
val widths = FloatArray(prefix.length)
var textWidth = 0f
paint.getTextWidths(prefix, widths)
for (w in widths) {
textWidth += w
}
padding = compoundPaddingLeft.toFloat()
setPadding(
(textWidth + padding).toInt(),
paddingStart,
paddingTop,
paddingBottom
)
}
}
// get the text with prefix
fun completedText() = prefix + text.toString()
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment