EditTextPreference Disable Buttons?

后端 未结 2 1378
悲&欢浪女
悲&欢浪女 2021-02-10 21:48

I want to have an EditTextPreference that will disable the OK button if there is no text in the EditText field. I created a custom EditTextPreference class and I am able to get

2条回答
  •  北恋
    北恋 (楼主)
    2021-02-10 22:30

    Here is a code sample that enables/disables button depending on whether onCheckValue function returns true or false.

    public class ValidatedEditTextPreference extends EditTextPreference
    {
        public ValidatedEditTextPreference(Context ctx, AttributeSet attrs, int defStyle)
        {
            super(ctx, attrs, defStyle);        
        }
    
        public ValidatedEditTextPreference(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)
        {        
            return Strings.hasValue(value);
        }
    
        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();
        }    
    }
    

提交回复
热议问题