问题
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.
Here is what I have:
<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" />
Now in 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
}
}
}
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.
回答1:
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();
}
}
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.
来源:https://stackoverflow.com/questions/20820481/an-edittextpreference-with-minimum-character-requirement