Skip to content

Instantly share code, notes, and snippets.

@raystatic
Last active October 3, 2022 17:49
Show Gist options
  • Select an option

  • Save raystatic/7dd92fb55443b72d7850cf4ea6ee0421 to your computer and use it in GitHub Desktop.

Select an option

Save raystatic/7dd92fb55443b72d7850cf4ea6ee0421 to your computer and use it in GitHub Desktop.
class EditTextWithError(
context: Context,
attributeSet: AttributeSet
):FrameLayout(context,attributeSet) {
private var errorText = ""
private var linearLayout:LinearLayout
private var editText:EditText
private var linearLayoutWidth = WRAP_CONTENT
private var linearLayoutHeight = WRAP_CONTENT
private var linearLayoutMinWidth: Int?=null
private var hint = ""
init {
linearLayoutWidth = attributeSet.getAttributeValue("http://schemas.android.com/apk/res/android", "layout_width").toIntOrNull() ?: 0
linearLayoutHeight = attributeSet.getAttributeValue("http://schemas.android.com/apk/res/android", "layout_height").toIntOrNull() ?: 0
linearLayoutMinWidth = attributeSet.getAttributeValue("http://schemas.android.com/apk/res/android", "minWidth").toIntOrNull()
if (linearLayoutMinWidth!=null){
linearLayoutWidth = linearLayoutMinWidth!!
}
hint = attributeSet.getAttributeValue("http://schemas.android.com/apk/res/android", "hint")
linearLayout = LinearLayout(context)
linearLayout.orientation = LinearLayout.VERTICAL
val relativeLayout = RelativeLayout(context)
relativeLayout.background = ContextCompat.getDrawable(context,R.drawable.rounded_gray_bg)
relativeLayout.setPadding(dpToPx(16f), dpToPx(16f), dpToPx(16f),dpToPx(16f).toInt())
editText = EditText(context)
editText.background = null
editText.hint = hint
editText.setPadding(0,0,0,0)
relativeLayout.addView(editText, linearLayoutWidth, linearLayoutHeight)
linearLayout.addView(relativeLayout, linearLayoutWidth, linearLayoutHeight)
context.obtainStyledAttributes(attributeSet,R.styleable.EditTextWithError).let {
errorText = it.getString(R.styleable.EditTextWithError_error).orEmpty()
showError(errorText)
addView(linearLayout,linearLayoutWidth, linearLayoutHeight)
it.recycle()
}
}
fun showError(error:String){
errorText = error
if (errorText.isNotEmpty()){
val errorTextView = AppCompatTextView(context)
errorTextView.text = errorText
errorTextView.setTextColor(ContextCompat.getColor(context,R.color.orange))
errorTextView.textSize = 14f
errorTextView.setPadding(dpToPx(4f), dpToPx(8f),0,0)
if (linearLayout[linearLayout.childCount - 1] !is TextView){
linearLayout.addView(errorTextView, WRAP_CONTENT, WRAP_CONTENT)
}
}
}
private fun dpToPx(dp:Float): Int {
val displayMetrics: DisplayMetrics = context.resources.displayMetrics
return (dp * (displayMetrics.xdpi / DisplayMetrics.DENSITY_DEFAULT)).roundToInt()
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment