If you check the docs for EditText , you’ll find a setText() method. It also inherits TextView ‘s setText(CharSequence) and setText(int) methods, so you can set it just like a regular TextView : This is the solution in Kotlin
MainActivity.kt
package com.jigopost.edittext
import android.os.Bundle
import android.text.InputType
import android.text.method.DigitsKeyListener
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 edit text digits programmatically
editText.inputType = InputType.TYPE_CLASS_NUMBER
editText.keyListener = DigitsKeyListener.getInstance("012345.")
}
}
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: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" />
<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="#483D8B"
android:textSize="26sp"
android:text="Allowed only '012345.'"
app:layout_constraintEnd_toEndOf="parent"
app:layout_constraintStart_toStartOf="parent"
app:layout_constraintTop_toBottomOf="@+id/editText"
tools:text="TextView" />
</androidx.constraintlayout.widget.ConstraintLayout>
Output