P
P
Pavel2015-01-23 08:14:27
Android
Pavel, 2015-01-23 08:14:27

How to enable a button while typing in a textbox?

When the application starts, an alertDialog is displayed with an input field and one button.
The button is disabled by default (The field must contain at least some text)
When entering text, the field must be checked, and if it contains at least one character, then the button should be made active.

AlertDialog addLessonDialog = addLessonDialogBuilder.create();
addLessonDialog.show();

final Button addLessonBtn = addLessonDialog.getButton(AlertDialog.BUTTON_POSITIVE);
addLessonBtn.setEnabled(false);

lessonNameFld.setOnKeyListener(new View.OnKeyListener(){
    @Override
    public boolean onKey(View v, int keyCode, KeyEvent event) {
        if (event.getAction() == KeyEvent.ACTION_UP) {
            addLessonBtn.setEnabled(true);
            if (lessonNameFld.getText().toString().isEmpty()) {
                addLessonBtn.setEnabled(false);
            }
        }
        return false;
    }
});

Issue: This works with a physical keyboard, the on-screen keyboard enables the button only after hitting enter

Answer the question

In order to leave comments, you need to log in

1 answer(s)
P
Paul, 2015-01-23
@PaulTMatik

He asked, he answered.
It is used just the same for processing hardware keyboard clicks. In my case, it was just necessary to track changes using textWatcher()

lessonNameFld.addTextChangedListener(new TextWatcher() {
    @Override
    public void afterTextChanged(Editable s) {
        addLessonBtn.setEnabled(true);
        if (lessonNameFld.getText().toString().isEmpty()) {
            addLessonBtn.setEnabled(false);
        }
    }
}

Didn't find what you were looking for?

Ask your question

Ask a Question

731 491 924 answers to any question