Android 具有最小字符要求的EditTextPreference
我有一个Android 具有最小字符要求的EditTextPreference,android,string,android-edittext,preferences,Android,String,Android Edittext,Preferences,我有一个EditTextPreference,我允许用户使用它设置应用程序的密码。我想要一个4位数的密码。我在xml文件中设置了maxLength=“4”。现在我的问题是不允许提交,除非输入的密码是4位数长 以下是我所拥有的: <EditTextPreference android:defaultValue="" android:dependency="EnablePasscode" android:dialogMe
EditTextPreference
,我允许用户使用它设置应用程序的密码。我想要一个4位数的密码。我在xml文件中设置了maxLength=“4”
。现在我的问题是不允许提交,除非输入的密码是4位数长
以下是我所拥有的:
<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" />
如果它说returntrue
comment out,我不知道该如何处理;我知道我不会返回;如果长度为4,我希望它提交对话框,否则如果长度为0、1、2或3,则抛出一个toast
。我在哪里以及如何做到这一点
更新:要验证此首选项,我需要控制我没有的OK按钮;这可能是一个解决办法
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
在这里被扩展。这很接近,但是当你按下对话框中的OK按钮时,它仍然提交(尽管祝酒是准确的)。我认为关键是控制OK按钮,它可能与EditTextPreference
不同,后者更适合EditText
视图。我在xml中没有看到任何对话框。到底是什么问题?使用EditTextPreference
,当用户在设置中单击它时,它会打开一个带有EditText
字段的对话框,以及两个按钮:确定和取消。我没有对这个进行编程;这是xml中的默认行为。我认为在Java中,我必须找到一种方法来访问它的按钮的控制。我改变了答案。试着看看它是否适合你。preference.setText(null);将这一行添加到代码中。核对答案
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();
}
}