填充EditText并按下新键时如何捕获事件?

时间:2018-10-04 15:09:04

标签: android android-edittext keypress

<EditText
    android:id="@+id/name"
    android:layout_width="wrap_content"
    android:layout_height="wrap_content"
    android:imeOptions="actionNext"
    android:inputType="textNoSuggestions|textCapCharacters"
    android:maxLength="3"
    android:hint="ABC"
    />

EditText中的所有3个符号都填满时,还有一个name应该聚焦。

name.addTextChangedListener(object: TextWatcher {
    override fun afterTextChanged(s: Editable?) {
        // Move to surname when all three symbols are entered.
        if (name.text.toString().length == 3) {
            surname.requestFocus()
        }
    }

    override fun beforeTextChanged(s: CharSequence?, start: Int, count: Int, after: Int) { }

    override fun onTextChanged(s: CharSequence?, start: Int, before: Int, count: Int) { }
})

当我们输入1、2和3个符号时,它可以正常工作。但是,当我们在name中选择最后一个位置时,在键盘上按一个新字母,则什么也没有发生。我试图抓住一个按键

name.setOnKeyListener { v, keyCode, event ->
    if (name.text.getText().length == 3) {
        surname.requestFocus()
    }
    false
}

但不会发生任何事件。如何移动焦点?

3 个答案:

答案 0 :(得分:1)

maxLength更改为4

android:maxLength="4"

afterTextChanged中:

 override fun afterTextChanged(s: Editable?) {
    // Move to surname when all three symbols are entered.
    if (name.isFocused() && name.text.toString().length > 3) {
        surname.requestFocus();
        name.setText(s.toString().substring(0,3));

    }
}

答案 1 :(得分:0)

在beforeTextChanged()中添加一个检查,以确保char序列的长度已经是3个字符,如果是,则要求关注姓氏

答案 2 :(得分:0)

根据@nupadhyaya的回答,我是这样的。

1)删除了android:maxLength="3"(或可以设置android:maxLength="4")。

2)为新符号添加了一个事件:

name.addTextChangedListener(object: TextWatcher {
    override fun afterTextChanged(s: Editable?) {
        val text = name.text.toString()
        if (text.length >= 3) {
            surname.requestFocus()
            if (text.length > 3) {
                // Remove symbols after third.
                name.setText(text.substring(0, 3))
            }
        }

        override fun beforeTextChanged(s: CharSequence?, start: Int, count: Int, after: Int) { }

        override fun onTextChanged(s: CharSequence?, start: Int, before: Int, count: Int) { }
    })
}

3)为姓氏中的Backspace键添加了一个事件:

surname.setOnKeyListener { _, keyCode, _ ->
    if (keyCode == KeyEvent.KEYCODE_DEL && surname.text.toString().isEmpty()) {
        // Move to the last symbol of name.
        name.requestFocus()
        name.setSelection(name.text.toString().length)
    }
    false
}