我怎样才能正确获取android偏好的值?个人错误

时间:2014-11-13 19:48:51

标签: android

我将使用此代码获取首选项的值,但是当我显示值1时,获得的值是默认值,如“false”,“vectorial”或“1”。 我将展示偏好的实际价值。 我知道,stackoverflow中存在这个问题。但不是帮助我。 我的代码来阅读首选项:

SharedPreferences prefs = getSharedPreferences("preferences",Context.MODE_PRIVATE);             
                boolean musica = prefs.getBoolean("musica", false);
                String graficos =prefs.getString("graficos", "vectorial"); 
                int Fragmentos = prefs.getInt("fragmentos",1);

Toast.makeText(getApplicationContext(), 
                    String.valueOf(Fragmentos), Toast.LENGTH_LONG).show();  

首选项xml存在并经过测试。 首选项xml:

<?xml version="1.0" encoding="utf-8"?>
<PreferenceScreen xmlns:android="http://schemas.android.com/apk/res/android"
android:key="preferencias_principal" >
<PreferenceCategory android:title="Asteroides" >
    <CheckBoxPreference
        android:key="musica"
        android:summary="Se reproduce música de fondo"
        android:title="Reproducir música" />

    <ListPreference
        android:defaultValue="1"
        android:entries="@array/tiposGraficos"
        android:entryValues="@array/tiposGraficosValores"
        android:key="graficos"
        android:summary="Se escoge la representación de gráficos"
        android:title="Tipo de gráficos" />

    <EditTextPreference
        android:defaultValue="3"
        android:key="fragmentos"
        android:summary="En cuantos trozos se divide un asteroide"
        android:title="Número de Fragmentos" />
</PreferenceCategory>
<PreferenceCategory android:title="Modo multijugador" >
    <CheckBoxPreference
        android:key="multijugador"
        android:summary="Activa modo multijugador"
        android:title="Activar modo multijugador" />

    <EditTextPreference
        android:key="max_jugadores"
        android:summary="Número máximo de jugadores"
        android:title="Máximo de jugadores" />

    <ListPreference
        android:defaultValue="1"
        android:entries="@array/multijugador"
        android:entryValues="@array/multijugador_valores"
        android:key="tipo_conexion"
        android:summary="Tipo de conexión"
        android:title="Tipo de conexión" />
</PreferenceCategory>

我该怎么做?

抱歉我的英文

2 个答案:

答案 0 :(得分:1)

您需要使用PreferenceManager#getDefaultSharedPreferences()来检索应用程序的设置SharedPreferences。请参阅this article

答案 1 :(得分:1)

您在PreferenceActivity中使用的应用程序首选项将保存到可通过调用PreferenceManager#getDefaultSharedPreferences()访问的文件中。你应该

更改:

SharedPreferences prefs = getSharedPreferences("preferences",Context.MODE_PRIVATE);   

SharedPreferences sharedPrefs = PreferenceManager.getDefaultSharedPreferences(getApplicationContext());

阅读the docs了解更多