有没有办法完全摆脱偏好?似乎clear()和remove(key)并没有完全摆脱偏好。如果调用clear()然后调用SharedPreferences.contains(“ key”),则返回true。

注意,我也提交了clear()。

最佳答案

这是clear()的实现方式:

public Editor clear() {
    synchronized (this) {
        mClear = true;
        return this;
    }
}

public boolean commit() {
    //...
    synchronized (this) {
      if (mClear) {
        mMap.clear();
        mClear = false;
      }
    }
    //...
}


这是contains(String key)的实现方式:

 public boolean contains(String key) {
   synchronized (this) {
     return mMap.containsKey(key);
   }
 }


您可以自己查看代码here。 (请注意,清除所有首选项后,不会调用首选项更改侦听器)。

对我来说,实现看起来不错,并且很可能是您的代码有问题。
这是我的简短示例应用程序,用于验证clear()是否正常工作。

public class TestPrefClear extends Activity
{
    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);

        SharedPreferences prefs = PreferenceManager.getDefaultSharedPreferences(this);
        prefs.edit().putBoolean("TEST", true).commit();
        if(!prefs.contains("TEST")){
            throw new IllegalStateException();
        }
        prefs.edit().clear().commit();
        if(prefs.contains("TEST")){
            throw new IllegalStateException();
        }
    }
}

07-28 01:37
查看更多