2011-03-20 17 views
2

我有以下的EditText偏好如何在android EditTextPreference中驗證用戶輸入的有效年份?

<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年和當前年之間)。理想的做法是在用戶更改首選項時執行此操作。

我應該怎麼做?

回答

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

感謝。其實我也需要了解如何驗證值用戶輸入是數字的(看起來像沒有像isNumberic這樣的函數)。 – 2011-03-21 18:18:15

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

這不會工作,因爲你可以負值和numberSigned是不好的 – Phil 2013-09-11 08:53:00

0

字符串年= eyear.getText()的toString(); 如果(!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

我發佈這個答案,因爲它很容易驗證1900年和1999年之間的年份 – 2017-06-06 00:51:15

+0

雖然這段代碼可能回答這個問題,提供關於如何和/或者爲什麼它解決了這個問題將提高答案的長期價值 。 – thewaywewere 2017-06-06 01:12:22