开发者

How to validate that user input valid year in android EditTextPreference?

I have the following EditText preference

    <EditTextPre开发者_开发问答ference android:key="pref_movies_min_year"
        android:title="@string/pref_movies_min_year" 
        android:summary="@string/pref_movies_min_year_summary"
        android:defaultValue="1950"/>

I need to validate that user has input valid year (i.e. the value is numeric, 4 digits, between 1900 and current year). Ideally to do it when user changes the preference.

How should I do it?


You can implement a OnSharedPreferenceChangeListener to validate and let the user know they specified a bad value.

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.
        }
    }
});


You could use the XML property inputType and set it to numeric. Then combine that with an InputFilter to prevent going over 4 characters. Unfortunately, I think you will still have to implement a listener to validate it is exactly 4 characters.

Code:

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

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜