CoolMind
CoolMind

Reputation: 28865

How to catch event when EditText is filled and new key is pressed?

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

Also have another EditText that should be focused when all 3 symbols are filled in the 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) { }
})

It works right when we enter 1, 2 and 3 symbols. But when we select last position in name, press a new letter in a keyboard, nothing happens. I tried to catch a key press with

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

but an event doesn't arise. How to move focus?

Upvotes: 0

Views: 196

Answers (3)

CoolMind
CoolMind

Reputation: 28865

According to @nupadhyaya answer I made so.

1) Removed android:maxLength="3" (or can set android:maxLength="4").

2) Added an event for new symbols:

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) Added an event for Backspace key in surname:

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
}

Upvotes: 0

nupadhyaya
nupadhyaya

Reputation: 1944

Change maxLength to 4

android:maxLength="4"

In 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));

    }
}

Upvotes: 1

Brandon
Brandon

Reputation: 1417

Add a check in the beforeTextChanged() for if the char sequence is already 3 characters in length, if so then request focus on surname

Upvotes: 0

Related Questions