Friday, September 4, 2020

android kotlin - EditText hide error

MainActivity.kt

package com.example.jetpack

import android.os.Bundle
import android.text.Editable
import android.text.TextWatcher
import androidx.appcompat.app.AppCompatActivity
import kotlinx.android.synthetic.main.activity_main.*


class MainActivity : AppCompatActivity() {
    override fun onCreate(savedInstanceState: Bundle?) {
        super.onCreate(savedInstanceState)
        setContentView(R.layout.activity_main)

        // set hint for edit text
        editText.hint = "City name?"

        // add text changed listener on edit text
        editText.addTextChangedListener(object: TextWatcher{
            override fun beforeTextChanged(p0: CharSequence?,
                                           p1: Int, p2: Int, p3: Int) {
                // do something here
            }

            override fun onTextChanged(p0: CharSequence?,
                                       p1: Int, p2: Int, p3: Int) {
                var lettersOnly = true

                p0?.forEach {
                    if (it.isDigit()){
                        lettersOnly = false
                    }
                }

                if (lettersOnly){
                    // hide/remove error from edit text when all are letters
                    editText.error = null
                }else{
                    // set error on edit text when user enter any digit
                    editText.error = "Digit not allowed."
                }
            }

            override fun afterTextChanged(p0: Editable?) {
                // do something here
            }
        })
    }
}
activity_main.xml

<?xml version="1.0" encoding="utf-8"?>
<androidx.constraintlayout.widget.ConstraintLayout
    xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:app="http://schemas.android.com/apk/res-auto"
    xmlns:tools="http://schemas.android.com/tools"
    android:id="@+id/constraintLayout"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    android:background="#FEFEFA"
    tools:context=".MainActivity">

    <EditText
        android:id="@+id/editText"
        android:layout_width="0dp"
        android:layout_height="wrap_content"
        android:layout_marginStart="12dp"
        android:layout_marginEnd="12dp"
        android:padding="12dp"
        android:textSize="30sp"
        android:inputType="text|textVisiblePassword"
        android:fontFamily="sans-serif-condensed-medium"
        app:layout_constraintBottom_toBottomOf="parent"
        app:layout_constraintEnd_toEndOf="parent"
        app:layout_constraintStart_toStartOf="parent"
        app:layout_constraintTop_toTopOf="parent"
        app:layout_constraintVertical_bias="0.12" />

</androidx.constraintlayout.widget.ConstraintLayout>