我想要一个 EditTextPreference,如果 EditText 字段中没有文本,它将禁用 OK 按钮。我创建了一个自定义 EditTextPreference 类,我能够获取 EditText 对象并设置一个 TextWatcher,但我找不到禁用按钮的方法。看起来我只是无法访问对话框中的确定和取消按钮。
任何人都知道获得这些按钮或做我想做的事情的方法吗?
只有其他选择是尝试从头开始创建一个看起来像并模仿 EditTextPreference 的自定义对话框。
我想要一个 EditTextPreference,如果 EditText 字段中没有文本,它将禁用 OK 按钮。我创建了一个自定义 EditTextPreference 类,我能够获取 EditText 对象并设置一个 TextWatcher,但我找不到禁用按钮的方法。看起来我只是无法访问对话框中的确定和取消按钮。
任何人都知道获得这些按钮或做我想做的事情的方法吗?
只有其他选择是尝试从头开始创建一个看起来像并模仿 EditTextPreference 的自定义对话框。
这是一个代码示例,它根据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();
}
}
需要在preference.xml 中将旧的EditTextPreference 更改为新的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"/>