如何验证特定int范围的EditTextPreference值 [英] How to validate an EditTextPreference value for a specific int range
问题描述
我想验证一个 EditTextPreference
值是否在特定的 int
范围内(比如说1到22) 。我可以验证的唯一部分是 inputType
(仅限数字),在prefs.xml文件中包含以下xml声明。
I want to validate an EditTextPreference
value to be inside a specific int
range (lets say 1 to 22). The only part that I could validate was the inputType
(number only) with the following xml declaration in the prefs.xml file.
android:inputType =number
android:inputType="number"
我做的第二件事就是写 ListSettings
活动中的以下代码。
The second thing that I did is to write the following code in the ListSettings
activity.
public class ListSettings extends PreferenceActivity implements OnSharedPreferenceChangeListener{
@Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
addPreferencesFromResource(R.xml.prefs);
SharedPreferences sp = PreferenceManager.getDefaultSharedPreferences(this);
sp.registerOnSharedPreferenceChangeListener(this);
}
public void onSharedPreferenceChanged(SharedPreferences sp, String key) {
String value = sp.getString(key, null);
int intZoomValue = Integer.parseInt(value);
if (intZoomValue < 1 || intZoomValue > 22) {
Intent intent = new Intent().setClass(this, dialog.class);
// I want to call the dialog activity here...
}
}
并且dialog.class如下:
and the dialog.class is the following:
public class dialog extends Activity {
@Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
AlertDialog.Builder builder = new AlertDialog.Builder(this);
builder.setMessage("Please enter a value between 1-22!");
builder.setCancelable(true);
AlertDialog alert = builder.create();
alert.show();
}
}
我想要实现的是调用<$每当用户输入的值不在1-22范围内时,c $ c> dialog.class (警告对话框)。
What I want to achieve is to call the dialog.class
(the alert dialog box) whenever the user enters a value not in the range 1-22.
I无法真正理解如何以正确的方式进行验证。
I can't really understand how to validate with the proper way.
推荐答案
仅仅钳位值可能更加用户友好如果输入的值无效,则在允许的范围内,并通过Toast通知用户您已经这样做。
It might be more user-friendly to just clamp the value to the permitted range if an invalid value is entered, and notify the user with a Toast that you have done so.
如果您的范围很小,例如1-22 ,那么您甚至可以考虑使用 Spinner
而不是 EditText
,这样用户就无法输入无效值首先。
If your range is small, such as 1-22, then you may even consider using a Spinner
instead of an EditText
so that the user can't enter an invalid value in the first place.
这篇关于如何验证特定int范围的EditTextPreference值的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!