我正在开发一个应用程序,当用户想要重置他的密码时要求 OTP,为此我需要一个像附件图像中的文本...我想继续的是每个字母的单独 editText ,所有这些都以水平方向的线性布局排列,有一定的边距和最大长度为 1,因此每个 editText 中只能输入一个字母...这是正确的方法吗??有什么建议吗??
最佳答案
在所有这些答案之后,考虑到 UI/UX,我没有找到我想要的东西,元素的删除是有缺陷的,以至于要回到以前的 EditText
,当前EditText 不应为空。
这是我在 Kotlin 中实现的解决方案,它适用于通过按下键盘上的 Delete 键进行删除。此外,删除功能的实现方式是,当当前 EditText
为空并按下 Delete 键时,它会切换回上一个 EditText
并同时删除其元素。
这样调用函数:
//GenericTextWatcher here works only for moving to next EditText when a number is entered //first parameter is the current EditText and second parameter is next EditText editText1.addTextChangedListener(GenericTextWatcher(editText1, editText2)) editText2.addTextChangedListener(GenericTextWatcher(editText2, editText3)) editText3.addTextChangedListener(GenericTextWatcher(editText3, editText4)) editText4.addTextChangedListener(GenericTextWatcher(editText4, null)) //GenericKeyEvent here works for deleting the element and to switch back to previous EditText //first parameter is the current EditText and second parameter is previous EditText editText1.setOnKeyListener(GenericKeyEvent(editText1, null)) editText2.setOnKeyListener(GenericKeyEvent(editText2, editText1)) editText3.setOnKeyListener(GenericKeyEvent(editText3, editText2)) editText4.setOnKeyListener(GenericKeyEvent(editText4,editText3))
现在,将这两个类粘贴到您当前的类中
class GenericKeyEvent internal constructor(private val currentView: EditText, private val previousView: EditText?) : View.OnKeyListener{ override fun onKey(p0: View?, keyCode: Int, event: KeyEvent?): Boolean { if(event!!.action == KeyEvent.ACTION_DOWN && keyCode == KeyEvent.KEYCODE_DEL && currentView.id != R.id.editText1 && currentView.text.isEmpty()) { //If current is empty then previous EditText's number will also be deleted previousView!!.text = null previousView.requestFocus() return true } return false } } class GenericTextWatcher internal constructor(private val currentView: View, private val nextView: View?) : TextWatcher { override fun afterTextChanged(editable: Editable) { // TODO Auto-generated method stub val text = editable.toString() when (currentView.id) { R.id.editText1 -> if (text.length == 1) nextView!!.requestFocus() R.id.editText2 -> if (text.length == 1) nextView!!.requestFocus() R.id.editText3 -> if (text.length == 1) nextView!!.requestFocus() //You can use EditText4 same as above to hide the keyboard } } override fun beforeTextChanged( arg0: CharSequence, arg1: Int, arg2: Int, arg3: Int ) { // TODO Auto-generated method stub } override fun onTextChanged( arg0: CharSequence, arg1: Int, arg2: Int, arg3: Int ) { // TODO Auto-generated method stub } }
此外,要禁用可见光标,您可以在布局中的 EditText
标记中使用 android:cursorVisible="false"
或者可以使用 java 函数 setCursorVisible(false)
。
编辑:我正在使用股票小部件 EditTexts
所以如果你想在它们周围显示一个框,只需创建一个可绘制布局并将其设置为 的背景>EditTexts
并给它们一个 5dp 的内边距。这将创建一个盒子并使其看起来更酷。
关于android - 编辑 OTP 的文本,每个字母位于不同的位置,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/38872546/