2016-04-27 18 views
5

Ho un quasi idea semplice: Voglio generare un adattatore per uno spinner con l'API di associazione dati e un BindingAdapter. Qui è il codice XML voglio usare:Utilizzo di un BindingAdapter con un array di stringhe dalle risorse

<Spinner 
    android:id="@+id/country" 
    android:layout_width="wrap_content" 
    android:layout_height="wrap_content" 
    app:value="@{address.country}" 
    app:data="@{@array/countries}" 
    app:keys="@{@array/iso_3166_2}"/> 

Indirizzo: ecco un semplice classe che ha un campo chiamato country che è una stringa e conterrà una stringa ISO-3166-2. Per semplificare, i valori saranno "DE" o "US".

Questa è la mia semplificato arrays.xml:

<?xml version="1.0" encoding="utf-8"?> 
<resources> 
    <string-array name="iso_3166_2"> 
     <item>DE</item> 
     <item>US</item> 
    </string-array> 

    <string-array name="countries"> 
     <item>@string/country_DE</item> 
     <item>@string/country_US</item> 
    </string-array> 
</resources> 

per il legame che ho scritto questo BindingAdapter:

@BindingAdapter({"value", "data", "keys"}) 
public static void generateAdapter(Spinner spinner, 
            String value, 
            @ArrayRes int data, 
            @ArrayRes int keys) { 

} 

Quando provo a compilare il codice ottengo questo errore:

Error:Execution failed for task ':app:compileDebugJavaWithJavac'.
java.lang.RuntimeException: Found data binding errors.
****/ data binding error ****msg:Identifiers must have user defined types from the XML file. countries is missing it
file:path/to/the/spinner-above.xml
loc:95:31 - 95:39
****\ data binding error ****

La riga 95 del mio xml è questa riga: app:value="@{address.country}"

Vedete cosa sto facendo male?

A proposito, non sono sicuro che le annotazioni relative alle risorse dell'array siano corrette? Non trovo il modo di limitarlo a un array di stringhe.

risposta

5

è possibile ottenerlo facendo riferimento a stringArray anziché a array. Ecco cosa ho fatto con recyclerView per ottenere valore dalle risorse e funziona perfettamente, potrebbe aiutarti anche tu.

in string.xml

<string-array name="myItems"> 
    <item>Item 1</item> 
    <item>Item 2</item> 
    <item>Item 3</item> 
    <item>Item 4</item> 
    <item>Item 5</item> 
    <item>Item 6</item> 
</string-array> 

in layout.xml

app:entries="@{@stringArray/fi}" 

nel tuo caso può essere app:data="@{@stringArray/countries}" o app:keys="@{@stringArray/iso_3166_2}".

e nel metodo di rilegatura

@BindingAdapter({"entries"}) 
public static void entries(RecyclerView recyclerView, String[] array) { 
    //get all values in array[] variable. 
} 

riferiscono this di più.

+1

Interessante Lo controllerò. Si! Funziona :-D – rekire