
- Forum-Beiträge: 434
26.11.2014, 21:34:38 via Website
26.11.2014 21:34:38 via Website
Hallo,
ich möchte kurz mal ein Snippet vorstellen und hoffe, dass es der ein oder andere gut gebrauchen kann.
Geht um das Initialisieren von Ressourcen in einem Layout. Gerade wenn man mal eine Activity hat wo mal wieder "alles zusammen läuft" ist einfacher, schneller Code gefragt. Hier das Beispiel anhand von ein paar View-Objekten:
die xml (unvollständig...)
<TextView
android:id="@+id/alarmprompt0"
android:layout_width="fill_parent"
android:layout_height="wrap_content"
android:textAppearance="@android:style/TextAppearance.Medium"
android:textColor="#000000"/>
<TextView
android:id="@+id/alarmprompt1"
android:layout_width="fill_parent"
android:layout_height="wrap_content"
android:textAppearance="@android:style/TextAppearance.Medium"
android:textColor="#000000"/>
<TextView
android:id="@+id/alarmprompt2"
android:layout_width="fill_parent"
android:layout_height="wrap_content"
android:textAppearance="@android:style/TextAppearance.Medium"
android:textColor="#000000"/>
<TextView
android:id="@+id/alarmprompt3"
android:layout_width="fill_parent"
android:layout_height="wrap_content"
android:textAppearance="@android:style/TextAppearance.Medium"
android:textColor="#000000"/>
Vielleicht ist ja hier schon dem ein oder anderen aufgefallen, dass die IDs alle recht ähnlich benannt sind. Das hat hier ausnahmsweise mal einen Sinn und ist nicht der Faulheit geschuldet. Denn in der .java werden die Views schließlich wie folgt geladen.
/* Initialisierung der TextViews über eine Loop */
for (int i = 0; i < AMOUNT_OF_VALUES; i++)
mTextView[i] = new TextView(this);
String ids[] = new String[AMOUNT_OF_VALUES];
for (int i = 0; i < AMOUNT_OF_VALUES; i++)
ids[i] = "alarmprompt" + Integer.toString(i);
for (int i = 0; i < AMOUNT_OF_VALUES; i++) {
int resID = getResources().getIdentifier(ids[i], "id", "xyz.deine.app");
mTextView[i] = (TextView) findViewById(resID);
}
mTextView[9].setText("Hello");
Global ist in der Java Klasse natürlich noch das Array bekannt gemacht geworden und praktischerweise noch eine Konstante, die die Anzahl der Elemente hält. Also so:
static final int AMOUNT_OF_VALUES = 11;
TextView mTextView[] = new TextView[AMOUNT_OF_VALUES];
Viel Spaß damit
Open Source