Tuesday, September 1, 2020

EditText numbers only programmatically Android kotlin

MainActivity.kt

class MainActivity : AppCompatActivity() {

    override fun onCreate(savedInstanceState: Bundle?) {

        super.onCreate(savedInstanceState)

        setContentView(R.layout.activity_main)


        // allow positive and negative decimal or integer numbers only

        editText.inputNumbersOnly()

    }

}


fun EditText.inputNumbersOnly(){

    inputType =

        InputType.TYPE_CLASS_NUMBER or // allow numbers

            InputType.TYPE_NUMBER_FLAG_DECIMAL or // allow decimal numbers

            InputType.TYPE_NUMBER_FLAG_SIGNED // allow positive and negative numbers

}

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"

        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>

Image:

EditText numbers only programmatically Android kotlin

 

No comments:

Post a Comment