具有最小字符要求的EditTextPreference [英] An EditTextPreference with Minimum character requirement
问题描述
我有一个EditTextPreference
,我可以用来设置应用程序的密码.我想要一个4位数的密码.我在xml文件中设置了maxLength = "4"
.现在,我的问题是除非输入的密码长4位数字,否则不允许提交.
I have an EditTextPreference
that I user to allow use to set a passcode to an app. I want to require a 4-digit passcode. I set the maxLength = "4"
in the xml file. Now I have the problem to not allow submit unless the entered passcode is 4 digits long.
这就是我所拥有的:
<EditTextPreference
android:defaultValue=""
android:dependency="EnablePasscode"
android:dialogMessage="Add a numeric passcode to provide access to enter the app. The passcode must be 4 digits."
android:dialogTitle="Set Passcode"
android:inputType="number"
android:key="passcode"
android:maxLength="4"
android:password="true"
android:title="Set Passcode" />
现在使用Java:
public void onSharedPreferenceChanged(SharedPreferences sharedPreferences,
String key) {
if (key.equals("passcode")) {
EditTextPreference setPasscode = (EditTextPreference) findPreference("passcode");
if (setPasscode.getText().toString().length() == 4) {
// return true
}
}
}
在说出return true
的地方将其注释掉,我不确定该如何处理.我知道我不做return
;我想要它如果长度为4则提交对话框,否则如果它为0、1、2或3,则抛出toast
.我在哪里以及如何去做?
Where it says return true
comment out, I am not sure how to handle this; I know I don't do a return
; what I want it it to submit the Dialog Box if length is 4, otherwise if it is 0, 1, 2, or 3, throw a toast
. Where and how can I do that?
更新:要验证此首选项,我需要控制我没有的确定"按钮; 这可能是一种解决方法. >
UPDATE: TO validate this preference, I need control of the OK button which I do not have; this may be a workaround.
推荐答案
private EditTextPreference preference;
this.preference = ((EditTextPreference) getPreferenceScreen() //put this in the onCreate
.findPreference("passcode"));
if (key.equals("passcode")) {
EditTextPreference setPasscode = (EditTextPreference) findPreference("passcode");
if (sharedPreferences.getString("passcode","0").length() != 4) {
Toast.makeText(this, "Should be 4 digits", Toast.LENGTH_LONG).show();
this.preference.setText(null);
return;
}else{
Toast.makeText(this, "Success!", Toast.LENGTH_LONG).show();
}
}
类似的东西应该可以为您提供帮助.请记住,不建议使用getPreferenceScreen
,建议使用PreferenceFragment
.我假设PreferenceActivity
正在此处扩展.
something like this should help you. Do keep in mind that getPreferenceScreen
is deprecated, it is recommended to use PreferenceFragment
. I am assuming that PreferenceActivity
is being extended here.
这篇关于具有最小字符要求的EditTextPreference的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!