如果EditText字段中没有文本,我想要一个EditTextPreference来禁用OK按钮。我创建了一个自定义的EditTextPreference类,我可以获取EditText对象并设置TextWatcher,但我找不到禁用该按钮的方法。看起来我只是无法访问对话框中的“确定”和“取消”按钮。
任何人都知道如何获得这些按钮或做我想做的事情?
只有其他选择是尝试从头开始创建一个看起来像模仿EditTextPreference的自定义Dialog。
答案 0 :(得分: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();
}
}
答案 1 :(得分:1)
需要将旧的EditTextPreference更改为preference.xml中的新ValidatedEditTextPreference。
我做了以下事情:
旧代码:
<EditTextPreference
android:dialogMessage="Please input your email"
android:dialogTitle="Set email"
android:key="Email"
android:summary="Your email"
android:title="-Missed call send to" android:defaultValue="xxx@xxx.xxx"/>
新代码:
<com.tanggod.missedcall2mail.ValidatedEditTextPreference
android:dialogMessage="Please input your email"
android:dialogTitle="Set email"
android:key="Email"
android:summary="Your email"
android:title="-Missed call send to" android:defaultValue="xxx@xxx.xxx"/>