androidandroid-alertdialogpreferenceactivityedittextpreference

How to set null validation in edittextpreference dialog


How to set null validation in edittextpreference dialog so that if it is null, the user should not be able to click ok and some message should be displayed in the dialog itself. I have been trying to find it for a long time but no success....


Solution

  • When edittext is null then ok button will be disabled and as soon as the text is entered it will be enabled::

    public class CustomEditTextPreference extends EditTextPreference implements
            OnClickListener {
    
    
            public CustomEditTextPreference(Context ctx, AttributeSet attrs, int defStyle)
            {
                super(ctx, attrs, defStyle);        
            }
    
            public CustomEditTextPreference(Context ctx, AttributeSet attrs)
            {
                super(ctx, attrs);                
            }
    
            private class EditTextWatcher implements TextWatcher
            {    
                @Override
                public void onTextChanged(CharSequence s, int start, int before, int count){}
    
                @Override
                public void beforeTextChanged(CharSequence s, int start, int before, int count){}
    
                @Override
                public void afterTextChanged(Editable s)
                {        
                    onEditTextChanged();
                }
            }
            EditTextWatcher m_watcher = new EditTextWatcher();
    
            /**
             * Return true in order to enable positive button or false to disable it.
             */
            protected boolean onCheckValue(String value)
            {        
                if (value.trim().equals(""))
                {
                    return false;
                }
                return true;
            }
    
            protected void onEditTextChanged()
            {
                boolean enable = onCheckValue(getEditText().getText().toString());
                Dialog dlg = getDialog();
                if(dlg instanceof AlertDialog)
                {
                    AlertDialog alertDlg = (AlertDialog)dlg;
                    Button btn = alertDlg.getButton(AlertDialog.BUTTON_POSITIVE);
                    btn.setEnabled(enable);                
                }
            }
    
            @Override
            protected void showDialog(Bundle state)
            {
                super.showDialog(state);
    
                getEditText().removeTextChangedListener(m_watcher);
                getEditText().addTextChangedListener(m_watcher);
                onEditTextChanged();
            }    
        }