how to identify input from keyboard that is number or not and then change UI according that ,, reference taken from phonepe

 1- Xml Code 

<?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:layout_width="match_parent"
android:layout_height="wrap_content"
android:layout_marginStart="10dp"
android:layout_marginTop="10dp"
android:layout_marginEnd="10dp"
tools:context=".TryToggle">

<EditText
android:id="@+id/etEntNumber"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:layout_marginStart="10dp"
android:layout_marginEnd="10dp"
android:hint="Enter NUmber"
app:layout_constraintEnd_toEndOf="parent"
app:layout_constraintStart_toStartOf="parent"
app:layout_constraintTop_toTopOf="parent" />

<Button
android:id="@+id/btnVisibal"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_marginTop="15dp"
android:gravity="center"
android:text="Working"
android:textStyle="bold"
android:visibility="gone"
app:layout_constraintEnd_toEndOf="parent"
app:layout_constraintStart_toStartOf="parent"
app:layout_constraintTop_toBottomOf="@id/etEntNumber" />

</androidx.constraintlayout.widget.ConstraintLayout>

2-Logic for Identify user input is Number or not and show different different design according to user input:

switchOnOff.addTextChangedListener ( object : TextWatcher{
override fun beforeTextChanged(p0: CharSequence?, p1: Int, p2: Int, p3: Int) {

}

override fun onTextChanged(userInput: CharSequence?, p1: Int, p2: Int, p3: Int) {
val inputText = userInput.toString().trim()
if (!inputText.isNullOrEmpty()){
if (isNumeric(inputText)){
btnVisibal.visibility= View.VISIBLE
}else{
btnVisibal.visibility= View.GONE
}
}

}

override fun afterTextChanged(p0: Editable?) {

}
})
fun isNumeric(str: String): Boolean {
return str.toDoubleOrNull() != null
}

Rajeshbhatt12

My name is Rajesh Bhatt. I am working as a senior android developer . I have created this blog for kotlin ,java and Android Development interview questions etc..

Previous Post Next Post