如何在android EditTextPreference中验证用户输入有效年份?

时间:2011-03-20 12:03:47

标签: android validation date

我有以下EditText首选项

    <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和当前年份之间)。理想情况下,当用户更改首选项时,请执行此操作。

我该怎么做?

3 个答案:

答案 0 :(得分:2)

您可以实现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.
        }
    }
});

答案 1 :(得分:2)

您可以使用XML属性inputType并将其设置为数字。然后将其与InputFilter组合以防止超过4个字符。不幸的是,我认为你仍然需要实现一个监听器来验证它正好是4个字符。

代码:

<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"
    />

答案 2 :(得分:0)

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");