2011-03-08 6 views
23

Estoy creando listas en una preferencia compartida y cuando se llama al método onPreferenceChanged() Deseo extraer el índice del elemento en la lista o un valor entero en algunos casos. Estoy tratando de construir los datos XML de la siguiente manera:Obteniendo valores enteros o de índice de una preferencia de lista

en las matrices:

<string-array name="BackgroundChoices"> 
    <item>Dark Background</item> 
    <item>Light Background</item> 
</string-array> 
<array name="BackgroundValues"> 
    <item>1</item> 
    <item>0</item> 
</array> 
<string-array name="SpeedChoices"> 
    <item>Slow</item> 
    <item>Medium</item> 
    <item>Fast</item> 
</string-array>  
<array name="SpeedValues"> 
    <item>1</item> 
    <item>4</item> 
    <item>16</item> 
</array> 

en el archivo de preferencias xml:

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

<ListPreference 
     android:key="keyBackground" 
     android:entries="@array/BackgroundChoices" 
     android:summary="Select a light or dark background." 
     android:title="Light or Dark Background" 
     android:positiveButtonText="Okay" 
     android:entryValues="@array/BackgroundValues"/> 
<ListPreference 
     android:key="keySpeed" 
     android:entries="@array/SpeedChoices" 
     android:summary="Select animation speed." 
     android:title="Speed" android:entryValues="@array/SpeedValues"/> 
</PreferenceScreen> 

Así que mi xml no funciona. Sé cómo hacer esto usando una matriz de cadenas en lugar de una matriz para los valores. Y podría extraer las cadenas de valor y obtener lo que quiero de eso, pero preferiría (si fuera posible) poder tener listas donde los valores fueran enteros, booleanos o enumeraciones. ¿Cuál es la forma habitual de hacer esto?

gracias de antemano,

Jay

Respuesta

40

Pon las preferencias en lo String y utilizan Integer.parseInt(). Creo que en realidad hay un informe de error sobre la limitación a la que se refiere, pero no puedo encontrar el enlace. Por experiencia, puedo decirte que solo uses Strings y te ahorres mucha frustración.

Nota para otros usuarios de SO, si puede probar que estoy equivocado, lo agradezco.

+0

Bueno, eso es un poco molesto. – theblang

10

Andrew era correcto, el hilo es here:

todavía está siendo comentada, y sin embargo ningún cambio (a partir de 2.3.3 de todos modos).

Integer.parseInt() de .valueOf() tendrá que funcionar. Si valueOf() funciona sin error, úselo, ya que no asigna tanto como parseInt(), es útil cuando NECESITA evitar GC como yo.

+0

Creo que está confundiendo valueOf() y parseInt(). Observe que valueOf() se implementa internamente como: new Integer (Integer.parseInt (i)); // con algo de almacenamiento en caché, aunque – auval

5

Basado en ListPreference de Android, creé IntListPreference. El uso es directo conducir - en pocas palabras este fragmento en sus preferencias xml:

<org.bogus.android.IntListPreference 
    android:key="limitCacheLogs" 
    android:defaultValue="20" 
    android:entries="@array/pref_download_logs_count_titles" 
    android:entryValues="@array/pref_download_logs_count_values" 
    android:negativeButtonText="@null" 
    android:positiveButtonText="@null" 
    android:title="@string/pref_download_logs_count" 
/>  

y que en strings.xml

<string name="pref_download_logs_count">Number of logs per cache</string> 
<string-array name="pref_download_logs_count_titles"> 
    <item>10</item> 
    <item>20</item> 
    <item>50</item> 
    <item>Give me all!</item> 
</string-array> 
<integer-array name="pref_download_logs_count_values"> 
    <item>10</item> 
    <item>20</item> 
    <item>50</item> 
    <item>-1</item> 
</integer-array> 
0

Aquí es una clase ListIntegerPreference utilizo (escrito por com.android.support:preference-v7:24.0.0). Sobrescribe algunos métodos y convierte entre Integer y String donde sea posible, de modo que la base ListPreference no reconoce, que está trabajando con Integers en lugar de Strings.

public class ListIntegerPreference extends ListPreference 
{ 
    public ListIntegerPreference(Context context, AttributeSet attrs, int defStyleAttr, int defStyleRes) 
    { 
     super(context, attrs, defStyleAttr, defStyleRes); 
    } 

    public ListIntegerPreference(Context context, AttributeSet attrs, int defStyleAttr) 
    { 
     super(context, attrs, defStyleAttr); 
    } 

    public ListIntegerPreference(Context context, AttributeSet attrs) 
    { 
     super(context, attrs); 
    } 

    public ListIntegerPreference(Context context) 
    { 
     super(context); 
    } 

    @Override 
    protected void onSetInitialValue(boolean restoreValue, Object defaultValue) 
    { 
     int defValue = defaultValue != null ? Integer.parseInt((String)defaultValue) : 0; 
     int value = getValue() == null ? 0 : Integer.parseInt(getValue()); 
     this.setValue(String.valueOf(restoreValue ? this.getPersistedInt(value) : defValue)); 
    } 

    @Override 
    public void setValue(String value) 
    { 
     try 
     { 
      Field mValueField = ListPreference.class.getDeclaredField("mValue"); 
      mValueField.setAccessible(true); 
      Field mValueSetField = ListPreference.class.getDeclaredField("mValueSet"); 
      mValueSetField.setAccessible(true); 

      String mValue = (String)mValueField.get(this); 
      boolean mValueSet = (boolean)mValueSetField.get(this); 

      boolean changed = !TextUtils.equals(mValue, value); 
      if(changed || !mValueSet) 
      { 
       mValueField.set(this, value); 
       mValueSetField.set(this, mValueSet); 
       this.persistInt(Integer.parseInt(value)); 
       if(changed) { 
        this.notifyChanged(); 
       } 
      } 
     } 
     catch (NoSuchFieldException e) 
     { 
      e.printStackTrace(); 
     } 
     catch (IllegalAccessException e) 
     { 
      e.printStackTrace(); 
     } 
    } 
} 

estoy usando esto con la creación de ListPreferences valores a través de código, a modo de prueba. Puede funcionar de inmediato, o tal vez deba anular funciones adicionales. Si es así, este es un buen comienzo y te muestra cómo puedes hacerlo ...

Cuestiones relacionadas