Search code examples
androidtextviewandroid-custom-viewandroid-softkeyboard

Create Passcode view in Android


I want to create view in android that reads 4 character pass-code. I want to focus prev element when user press backspace. Is it possible to capture backspace event when selected view is empty?

I Also want to close/hide keyboard after last character is entered. Is it possible?


Solution

  • I have overwritten onKey & onFocusChange functions and used ZeroWidthString("\u200B") to capture Delete Event from Soft Keyboard. Following is the code sniff

    @Override
    public boolean onKey(View v, int keyCode, KeyEvent event) {
        if(event.getAction() == KeyEvent.ACTION_UP ) {
            TextView tv = (TextView) v;
            if (keyCode == KeyEvent.KEYCODE_DEL){
                if (tv.getText().toString().equalsIgnoreCase(ZeroWidthString))
                    moveToPrevField();
                else
                    tv.setText(ZeroWidthString);
            }
        }
    }
    
    @Override
    public void onFocusChange(View v, boolean hasFocus) {
        TextView tv = (TextView) v;
        if (hasFocus) {
            tv.setText(ZeroWidthString);
        }
        else if (tv.getText().toString().equalsIgnoreCase(ZeroWidthString)) {
            tv.setText("");
        }
    }