文本编辑中的行拖放android studio

j5fpnvbx  于 2021-09-23  发布在  Java
关注(0)|答案(1)|浏览(220)

你有什么建议吗 EditText 接收用户输入的大约9个字母(或数字)并在完成后(例如:单击某个按钮操作或丢失键盘焦点),它将更新其中的字母 EditText . 以下是要求:
输入: 123456789 输出:

123 
456 
789

在此处输入图像描述

c2e8gylq

c2e8gylq1#

请确认这是否是您想要实现的目标?
EditText ,你想要吗 EditText 能够为每3个字符添加换行符(多行)(在简单操作之后)
如果是,以下是一个可能解决潜在问题的自以为是的解决方案:

上面的截图写在这里
对于 EditText 第二部分,我们目前能想到的是:
从这里查看核心ktx扩展

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

为了可读性,上面代码片段中省略了几行,是的,也有一些代码会编译错误,需要相应地调整

相关问题