// 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 = "$userInput\n"
}
// 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" />
/>
1条答案
按热度按时间c2e8gylq1#
请确认这是否是您想要实现的目标?
有
EditText
,你想要吗EditText
能够为每3个字符添加换行符(多行)(在简单操作之后)如果是,以下是一个可能解决潜在问题的自以为是的解决方案:
上面的截图写在这里
对于
EditText
第二部分,我们目前能想到的是:从这里查看核心ktx扩展
为了可读性,上面代码片段中省略了几行,是的,也有一些代码会编译错误,需要相应地调整