Ich bin an die Felder eines Objekts - Zeichenfolgen, Ganzzahlen usw. - an eine Layoutdatei gebunden. Zum Beispiel:
<data>
<variable
name="appState"
type="com.example.app.AppState"
/>
</data>
Und
<android.support.v7.widget.Toolbar
android:id="@+id/toolbar"
android:layout_width="match_parent"
android:layout_height="?attr/actionBarSize"
android:background="?attr/colorPrimary"
android:title="@{appState.thing}"
/>
Das funktioniert gut. Ich habe aber auch eine HashMap
von Werten in diesem AppState-Objekt.
Ist es möglich, an Werte von diesem zu binden, d.h. android:text="@{appState.thehashmap["thekey"]"
?
Die jetzige Ausdruckssyntax scheint es nicht zu unterstützen.
Aber, frage ich mich, gibt es einen Weg? Danke vielmals.
Antworten:
1 für die Antwort № 1Okay, wenn man die Dokumente genauer betrachtet, ist es:
Wenn du HashMap
ist etwa so:
public HashMap<String, String> thing = new HashMap<String, String>() {{
put("stuff", "yeah");
}};
public HashMap<String, String> getThing() {
return thing;
}
public void setThing(HashMap<String, String> thing) {
this.thing = thing;
}
Dann kann Ihre Layoutdatei wie folgt aussehen:
<data>
<import type="java.util.HashMap"/>
<variable
name="appState"
type="com.example.app.AppState"
/>
</data>
...
<android.support.v7.widget.Toolbar
android:id="@+id/toolbar"
android:layout_width="match_parent"
android:layout_height="?attr/actionBarSize"
android:background="?attr/colorPrimary"
android:title="@{appState.thing["stuff"]}"
/>
0 für die Antwort № 2
Die einfachste Methode ist: Sie können sie direkt aufrufen []
Betreiber durch Bereitstellung key
Innerhalb []
.
Also, wenn Sie eine Karte wie folgt haben:
<data>
<import type="java.util.Map"/>
<variable name="map" type="Map<String, String>"/>
</data>
...
android:text="@{map[key]}"
Quelle: https://developer.android.com/topic/libraries/data-binding/index.html