Created
March 18, 2021 02:55
-
-
Save isfaaghyth/400078b7cd6d9e9e4ded05bf7e0b214f to your computer and use it in GitHub Desktop.
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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