Tuesday, September 1, 2020

How to EditText limit number range Android kotlin

How to EditText limit number range Android kotlin

MainActivity.kt

class MainActivity : AppCompatActivity() {

    override fun onCreate(savedInstanceState: Bundle?) {

        super.onCreate(savedInstanceState)

        setContentView(R.layout.activity_main)


        // apply edit text input filter number range

        editText.inputFilterNumberRange(6..90)


        // show the rule

        textView.text = "Input number range 6 to 90"

        textView.append("\n\nIf user put less than minimum then it set to minimum.")

    }

}



// extension function to filter edit text number range

fun EditText.inputFilterNumberRange(range: IntRange){

    filterMin(range.first)

    filters = arrayOf<InputFilter>(InputFilterMax(range.last))

}



// class to input filter maximum number

class InputFilterMax(private var max: Int) : InputFilter {

    override fun filter(

        p0: CharSequence,p1: Int,p2: Int,p3: Spanned?,p4: Int,p5: Int

    ): CharSequence? {

        try {

            val replacement = p0.subSequence(p1, p2).toString()

            val newVal = p3.toString().substring(0, p4) + replacement + p3.toString()

                .substring(p5, p3.toString().length)

            val input = newVal.toInt()

            if (input <= max) return null

        } catch (e: NumberFormatException) { }

        return ""

    }

}



// extension function to filter edit text minimum number

fun EditText.filterMin(min: Int){

    onFocusChangeListener = View.OnFocusChangeListener { view, b ->

        if (!b) {

            // set minimum number if inputted number less than minimum

            setTextMin(min)

            // hide soft keyboard on edit text lost focus

            context.hideSoftKeyboard(this)

        }

    }


    setOnEditorActionListener { v, actionId, event ->

        if (actionId == EditorInfo.IME_ACTION_DONE) {

            // set minimum number if inputted number less than minimum

            setTextMin(min)


            // hide soft keyboard on press action done

            context.hideSoftKeyboard(this)

        }

        false

    }

}



// extension function to set edit text minimum number

fun EditText.setTextMin(min: Int){

    try {

        val value = text.toString().toInt()

        setUnderlineColor(Color.GREEN)

        if (value < min){

            setText("$min")

            setUnderlineColor(Color.RED)

        }

    }catch (e: Exception){

        setUnderlineColor(Color.RED)

        setText("$min")

    }

}



// extension function to hide soft keyboard programmatically

fun Context.hideSoftKeyboard(editText: EditText){

    (getSystemService(INPUT_METHOD_SERVICE) as InputMethodManager).apply {

        hideSoftInputFromWindow(editText.windowToken, 0)

    }

}



// extension function to set/change edit text underline color

fun EditText.setUnderlineColor(color: Int){

    background.mutate().apply {

        if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.Q){

            colorFilter = BlendModeColorFilter(color, BlendMode.SRC_IN)

        }else{

            setColorFilter(color, PorterDuff.Mode.SRC_IN)

        }

    }

}

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"

    android:clickable="true"

    android:focusable="true"

    android:focusableInTouchMode="true"

    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:inputType="number"

        android:padding="12dp"

        android:textSize="30sp"

        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" />


    <TextView

        android:id="@+id/textView"

        android:layout_width="0dp"

        android:layout_height="wrap_content"

        android:layout_marginTop="12dp"

        android:fontFamily="sans-serif-condensed-medium"

        android:gravity="center"

        android:padding="8dp"

        android:textColor="#4F42B5"

        android:textSize="25sp"

        app:layout_constraintEnd_toEndOf="parent"

        app:layout_constraintStart_toStartOf="parent"

        app:layout_constraintTop_toBottomOf="@+id/editText"

        tools:text="TextView" />


</androidx.constraintlayout.widget.ConstraintLayout>


No comments:

Post a Comment