Any suggestion how to have an EditText
that receiving user input around 9 letters (or digits) and after finish (e.g: click some button action or lost keyboard focus), it’ll update the letters inside that EditText
. Following are the requirements:
Input: 123456789
Output:
123 456 789
Advertisement
Answer
Please confirm if this is what you want to achieve?
There’s
EditText
, you want thatEditText
able to add newline (multiline) for every 3 character (after a simple actions)
If yes, here’s an opinionated solutions that might solve the underlying problems:
The above screenshot is written in here
For the EditText
part, what we can think of at the moment:
See Core-KTX extensions from here
// YourActivity.kt import androidx.core.widget.doAfterTextChanged import kotlin.text.buildString // this import is optional. to identify its origin override fun onCreate(...) { // assign your `editText` & `textView` variable with usual `findViewById` or using `ViewBinding` if your project already using it // Directly listen for user input in EditText editText?.doAfterTextChanged { userInput -> if (userInput.length == 3) textView?.text = "$userInputn" } // Or you can use the below approach: textView.text = buildString { editText?.toString()?.forEachIndexed { index, letter -> append(c) // index start from 0 // index+1 = 0+1, so we can start from 1-index // check for the reminder of index/3 == 0 // meaning we are appending the `n` (newline) to the text if ((index+1) % 3 == 0) append("n") } } } // your_activity.xml <LinearLayout ... <EditText ... id="@id/editText" /> // create below TextView as a result of user inputs <TextView ... id="@id/textView" /> />
A few lines in the above snippet code omitted for readability, and yes there’s a few code will compile-error as well, needs to adjust it accordingly