2013-10-15 21 views
0

在Android 4中,我有一個首選值,我想以標準格式E2C56DB5-DFFB-48D2-B060-D0F5A71096E0出現。但是用戶可以輸入沒有破折號的值。我想允許用戶輸入任何空格或破折號的組合,並簡單地讓我的代碼正常化它。是否可以在更改時規範化Android偏好值?

我使用下面的代碼,我看到日誌行,但它什麼都沒做。我猜測這是因爲Android有另一個編輯器對象打開覆蓋我的更改。有沒有其他方法可以實現這一點?

public class UuidFragment extends PreferenceFragment { 
    ... 
    @Override 
    public void onCreate(Bundle savedInstanceState) { 
     super.onCreate(savedInstanceState); 
     addPreferencesFromResource(R.xml.preferences); 
     this.getPreferenceScreen().findPreference("pref_uuid").setOnPreferenceChangeListener(new OnPreferenceChangeListener() { 
      @Override 
      public boolean onPreferenceChange(Preference preference, 
       Object newValue) { 
       if (newValue.toString().length() != 0) { 
        String normalizedUuid=normalizeUuid(newValue.toString()); 
        // TODO: this code runs but does nothing, I think because after committing the change, there is a higher level editor that commits the old value 
        // thereby undoing this change 
        if (!normalizedUuid.equals(newValue.toString())) { 
         Log.d(TAG, "Adjusting uuid from "+newValue.toString()+" to "+normalizedUuid); 
         SharedPreferences settings = PreferenceManager.getDefaultSharedPreferences(UuidFragment.this.getActivity()); 
         SharedPreferences.Editor editor = settings.edit(); 
         editor.putString(preference.getKey(), normalizedUuid); 
         editor.commit(); 
        } 
        return true; 
       } 
      } 
     }); 
} 

}

回答

1

嘗試子類EditTextPreference和壓倒一切的setText()。在您的setText()方法中,在鏈接到超類之前修正傳入的字符串。然後,從您的偏好XML中引用您的EditTextPreference子類。

相關問題