0

I want to create custom class which extends TextInputLayout and have sort of an access into its inner EditText, so I can set focus listener on it. Based on focus state and text in the EditText the error shows in TextInputLayout. Below is my current simple code where edit text is null. How can I achieve so have custom TextInputLayout that can communicate with its inner EditText ?

class CustomTextInputLayout : TextInputLayout {

    constructor(context: Context) : super(context)

    constructor(context: Context, attrs: AttributeSet) : super(context, attrs)

    init {
            Log.e("_TEST", this.editText?.toString() ?: "null") // gives null
            editText?.setOnFocusChangeListener { v, hasFocus ->
                if (hasfocus.not()) {
                    val textToCheck = editText?.text.toString()
                    this.error = someValidationFunction(textToCheck)
                }

            }
    }
}
<com.app.utility.CustomTextInputLayout
                android:layout_width="0dp"
                android:layout_height="wrap_content"
                app:layout_constraintEnd_toEndOf="parent"
                app:layout_constraintStart_toStartOf="parent">

            <com.google.android.material.textfield.TextInputEditText
                    android:layout_width="match_parent"
                    android:layout_height="wrap_content"/>

</com.app.utility.CustomTextInputLayout>
P.Juni
  • 2,365
  • 14
  • 26

1 Answers1

2

The editText isn't initialized in init method yet. First, the parent will be laid out then the child. Please, check this method

onLayout(boolean changed, int left, int top, int right, int bottom)

Views lifecycle is very important if you want to create custom views or viewgroups.

https://developer.android.com/reference/android/view/ViewGroup.html

minhazur
  • 4,928
  • 3
  • 25
  • 27