EditTextPreference禁用按钮?

Bob*_*Bob 4 android dialog preference android-edittext

我希望有一个EditTextPreference,如果EditText字段中没有文本,它将禁用OK按钮.我创建了一个自定义的EditTextPreference类,我可以获取EditText对象并设置TextWatcher,但我找不到禁用该按钮的方法.看起来我只是无法访问对话框中的"确定"和"取消"按钮.

任何人都知道如何获得这些按钮或做我想做的事情?

只有其他选择是尝试从头开始创建一个看起来像模仿EditTextPreference的自定义Dialog.

ina*_*ruk 9

这是一个代码示例,根据onCheckValue函数是返回true还是启用/禁用按钮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();
    }    
}
Run Code Online (Sandbox Code Playgroud)