显示偏好活动的共享偏好

时间:2018-04-12 02:04:40

标签: android android-sharedpreferences

我正在努力弄清楚如何在偏好活动中显示偏好。我只是想显示高分并且我一直得到相同的345值。我已在调试中确认已保存新的高分。这是我的所有代码。

的preferences.xml

<Preference
    android:title="High Score"
    android:selectable="false"
    android:defaultValue="0"
    android:key="@string/pref_highest_score"/>

HighScoreActivity.java

public class HighScoreActivity extends PreferenceActivity {

@Override
protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);

    getFragmentManager().beginTransaction()
            .replace(android.R.id.content, new HighScoreFragment()).commit();
}

public static class HighScoreFragment extends PreferenceFragment implements SharedPreferences.OnSharedPreferenceChangeListener {

    @Override
    public void onResume(){
        super.onResume();
    }

    @Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        addPreferencesFromResource(R.xml.preferences);

    }

    @Override
    public void onSharedPreferenceChanged(SharedPreferences sharedPreferences, String key) {

    }
}
}

的strings.xml

<!-- High Score settings -->


<string name="pref_highest_score">345</string>
<string name="title_activity_high_score">High Score</string>

MainActivity.java

preferences = PreferenceManager.getDefaultSharedPreferences(context);
    Assets.highScore = preferences.getInt(context.getString(R.string.pref_highest_score), 1);
    editor = preferences.edit();
    editor.putInt(context.getString(R.string.pref_highest_score), currentPoints );
                        editor.apply();

1 个答案:

答案 0 :(得分:0)

这是因为您的偏好设置屏幕实际上并未获得pref_highest_score的值。您应该找到首选项并致电Preference.setSummary()。像:

@Override
public void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    addPreferencesFromResource(R.xml.preferences);

    // Gets the preference defined in XML
    Preference p = findPreference("@string/pref_highest_score");

    // Sets the summary of the preference to the high score
    p.setSummary(
          String.valueOf(preferences.getInt(context.getString(R.string.pref_highest_score), 1))
    );
}

其中preferencesPreferenceManager.getDefaultSharedPreferences(context)

在XML中,指定首选项的ID:

<Preference
    android:key="@string/pref_highest_score"
    android:title="High Score"
    android:selectable="false"
    android:defaultValue="0"/>