Search code examples
androidandroid-edittextgettext

Getting text from EditText without a button


In my app i create an EditText dynamically when a CheckBox is not checked and i want to get the text the user writes in it. The problem is that i don't know where to write the getText().toString(). I have debugged this and i see that when the EditText is created the getText().toString() is executed immediately and returns always "" . I have also tried the focusChange in the EditText but without any success. Any help is appreciated!

        final EditText editText = new EditText(this);
        TableRow.LayoutParams params = new TableRow.LayoutParams(getPx(100) , ViewGroup.LayoutParams.WRAP_CONTENT);
        params.setMargins(0 ,0 ,getPx(100) ,0);
        tr.addView(editText);
        date = editText.getText().toString();

Solution

  • Have you tried this:

             editText.addTextChangedListener(new TextWatcher() {
                @Override
                public void beforeTextChanged(CharSequence s, int start, int count, int after) {
    
                }
    
                @Override
                public void onTextChanged(CharSequence s, int start, int before, int count) {
                    if(isValidDate()) {
                       date = s.toString();
                    }
                }
    
                @Override
                public void afterTextChanged(Editable s) {
    
                }
            });
    
        ...
    
        private boolean isValidDate() {
           // implement your logic here
        }