如何在android EditTextPreference中验证用户输入的有效年份?
我有以下编辑文本首选项如何在android EditTextPreference中验证用户输入的有效年份?,android,validation,date,Android,Validation,Date,我有以下编辑文本首选项 <EditTextPreference android:key="pref_movies_min_year" android:title="@string/pref_movies_min_year" android:summary="@string/pref_movies_min_year_summary" android:defaultValue="1950"/> 我需要验证用户是否输入了有效年
<EditTextPreference android:key="pref_movies_min_year"
android:title="@string/pref_movies_min_year"
android:summary="@string/pref_movies_min_year_summary"
android:defaultValue="1950"/>
我需要验证用户是否输入了有效年份(即值为数字,4位,介于1900和当前年份之间)。理想情况下,当用户更改首选项时执行此操作
我应该怎么做?您可以实现OnSharedPreferenceChangeListener来验证并让用户知道他们指定了错误的值
SharedPreferences prefs = PreferenceManager.getDefaultSharedPreferences(this);
prefs.setOnSharedPreferenceChangeListener(new OnSharedPreferenceChangeListener() {
public void onSharedPreferenceChanged(SharedPreferences prefs, String key) {
if(key.equals("year") {
// check if a valid year and let the user know if it isn't.
}
}
});
可以使用XML属性并将其设置为数字。然后将其与一个字母组合,以防止超过4个字符。不幸的是,我认为您仍然需要实现一个侦听器来验证它是否正好是4个字符 代码:
谢谢。事实上,我还需要了解如何验证用户输入的值是否为数字(看起来没有类似isNumberic的函数)。这不会起作用,因为你可以使用负值和numberSigned。我发布这个答案是不好的,因为它很容易验证1900年和1999年之间的年份,而这段代码可能会回答这个问题,提供关于如何和/或为什么解决问题的附加上下文将提高答案的长期价值。
<EditTextPreference android:key="pref_movies_min_year"
android:title="@string/pref_movies_min_year"
android:summary="@string/pref_movies_min_year_summary"
android:defaultValue="1950"
android:inputType="number"
android:maxLength="4"
/>
String year = eyear.getText().toString();
if (!year.subSequence(0, 2).equals("19") || year.length()!= 4) {
LayoutInflater layoutInflater = (LayoutInflater) getBaseContext()
.getSystemService(LAYOUT_INFLATER_SERVICE);
View popupView = layoutInflater.inflate(R.layout.helppop, null);
final PopupWindow popupWindow = new PopupWindow(popupView,
LayoutParams.WRAP_CONTENT, LayoutParams.WRAP_CONTENT);
ImageButton img = (ImageButton) popupView
.findViewById(R.id.imageButton1);
img.setBackground(getResources()
.getDrawable(R.drawable.warning));
TextView txt = (TextView) popupView.findViewById(R.id.helptxt);
txt.setText("the year you entert is incorret");