【问题标题】:Create multiple preferences android创建多个首选项android
【发布时间】:2014-06-02 20:57:08
【问题描述】:

在尝试创建我的应用的第二个偏好 Activity 时,我感到绝望。 我之前实现了一个 SharedPreferences,效果很好,但现在我正在尝试创建第二个偏好活动来处理特定的活动,但我无法使其正常工作。基本上发生的是,无论我选择哪种颜色,它总是给我“默认值”= 1,就好像它正在检查的首选项文件不存在一样。 这是我的preferenceActivity代码:

public class PreferenciasGrafica extends PreferenceActivity {


@Override protected void onCreate(Bundle savedInstanceState) {

      super.onCreate(savedInstanceState);

      addPreferencesFromResource(R.xml.preferencias_grafica);

   }

public void onBackPressed(){
    //Preferencias
             //PreferenceManager.getDefaultSharedPreferences(this);//Carga archivo preferencias
            SharedPreferences appPrefs2 =this.getPreferences(MODE_PRIVATE);
            int colore=Integer.parseInt(appPrefs2.getString("color","1"));//Pasa a samples las prefer. elegidas
            //startActivity(new Intent(this, Main.class));
            switch(colore){
            case 1:
                colore=Color.RED;
            break;
            case 2:
                colore=Color.BLUE;
            break;
            case 3:
                colore=Color.GREEN;
            break;
            }
            Grafica grafica=new Grafica(colore);
            //grafica.color=color;

            startActivity(new Intent(this, Grafica.class));

            finish();

  }
}

这是首选项文件的 xml:

    <PreferenceScreen 
  xmlns:android="http://schemas.android.com/apk/res/android" 
  android:key="preferencias_principal" > 

  <ListPreference 
   android:key="color" 
   android:title="Color de la gráfica" 
   android:summary="Selecciona el color a del gráfico" 
   android:entries="@array/colores"
   android:entryValues="@array/valores" 
   android:defaultValue="0"/> 

  </PreferenceScreen>

这是数组文件:

 <resources>
  <string-array name="colores"> 
     <item>Rojo</item> 
     <item>Azul</item> 
     <item>Verde</item>
  </string-array>
  <string-array name="valores"> 
     <item>1</item> 
     <item>2</item> 
     <item>3</item>
   </string-array>
</resources>

有人知道我在这里做错了什么吗?我完全被这个浪费了!

编辑:问题解决了!!只需更改它并使其如下所示:

SharedPreferences appPrefs2 =PreferenceManager.getDefaultSharedPreferences(this);

【问题讨论】:

    标签: android sharedpreferences preferences preferenceactivity


    【解决方案1】:

    尝试使用

      PreferenceManager.getDefaultSharedPreferences(getApplicationContext());
    

    当您获取 SharedPreferences 时。

    【讨论】:

    • 感谢上帝让我开心,我只需要这样说 SharedPreferences appPrefs2 =PreferenceManager.getDefaultSharedPreferences(this);
    猜你喜欢
    • 2014-05-03
    • 2013-04-13
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2012-09-08
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多