EditTextPreferences验证

时间:2013-07-20 02:40:18

标签: android validation sharedpreferences edittextpreference

有谁能告诉我这段代码有什么问题。由于某种原因,在更改值时未调用OnSharedPreferencesChanged。我正在尝试检查输入的PIN是否等于2位数或否。但是因为它不起作用.. 任何人都可以帮助我。

感谢!

import android.content.SharedPreferences;
import android.content.SharedPreferences.OnSharedPreferenceChangeListener;
import android.os.Bundle;
import android.preference.EditTextPreference;
import android.preference.Preference;
import android.preference.PreferenceActivity;
import android.util.Log;
import android.widget.Toast;

public class PrefsActivity extends PreferenceActivity implements
        OnSharedPreferenceChangeListener {

    EditTextPreference editPreference;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        addPreferencesFromResource(R.xml.prefs);
        this.editPreference = ((EditTextPreference) getPreferenceScreen()
                .findPreference("userPass"));
        Log.d("TAG","before sharedPreferenceChanged");
    }

    @Override
    protected void onResume() {
        super.onResume();
        // Set up a listener whenever a key changes
        getPreferenceScreen().getSharedPreferences()
                .registerOnSharedPreferenceChangeListener(this);
    }

    @Override
    protected void onPause() {
        super.onPause();
        // Unregister the listener whenever a key changes
        getPreferenceScreen().getSharedPreferences()
                .unregisterOnSharedPreferenceChangeListener(this);
    }

    @Override
    public void onSharedPreferenceChanged(SharedPreferences sharedPreferences,
            String key) {
        Log.d("TAG","In SharedPreferences");
        if (sharedPreferences.getString("userPass", null).length() != 2) {
            Log.d("TAG","lenght is less than 1");

            Toast.makeText(this, "Pin has to be 2 digits only",
                    Toast.LENGTH_LONG).show();
            this.editPreference.setText(null);
            return;
        } else {
            Toast.makeText(this, "Pin set", Toast.LENGTH_LONG).show();
        }
        // TODO Auto-generated method stub

    }

1 个答案:

答案 0 :(得分:0)

尝试在onCreate()中为editPreference设置setOnPreferenceChangeListener,将验证码放入此回调中。

阅读文档时,他们说当共享首选项发生更改(已更改)时会调用OnSharedPreferenceChangeListener。另一方面,当用户更改此首选项时(但在更新内部状态之前),会触发setOnPreferenceChangeListener“