2010-02-06 8 views
183

Sto scrivendo un'implementazione personalizzata di ListAdapter.Come ottenere un gonfiatore di layout dato un contesto?

Nel suo costruttore, sto prendendo in un contesto, un ID di risorsa (cioè R.id.xxx che rappresenta il file di layout), e un elenco e una mappa (questi contengono i dati).

Ora, il problema è che avrò bisogno di un LayoutInflater per ottenere l'oggetto View che si trova nel file XML del layout separato.

Come posso ottenere il LayoutInflater dato solo il contesto?

Ora, perché penso che questo sia possibile, è che questo è abbastanza simile a quello che viene passato al costruttore di un ArrayAdapter (contesto, risorsa, textViewResourceId, array di dati), e immagino che anche l'ArrayAdapter debba fare uso di un LayoutInflater dato solo un contesto.

Ma come può essere fatto?

risposta

450

È possibile utilizzare il staticfrom() method from the LayoutInflater class:

LayoutInflater li = LayoutInflater.from(context); 
+10

Grazie! stavo cercando di trovare Context.getSomething(). getAnotherThing(). getLayoutInflater()! –

+0

Questo è l'unico metodo che ha funzionato per me. Tutti gli altri che ho provato finora hanno lanciato un'eccezione. – num1

+0

La migliore soluzione, felice di essere il 200esimo sconto :) – tbraun

48

È inoltre possibile utilizzare questo codice per ottenere LayoutInflater:

LayoutInflater li = (LayoutInflater) context.getSystemService(Context.LAYOUT_INFLATER_SERVICE) 
+37

Qual è la differenza tra LayoutInflater.from (Context ctx) e questo getSustemService (...)? –

+8

+1, per una bella domanda, nell'attuazione del metodo LayoutInflater.from (context) chiama anche context.getSystemService() per ottenere LayoutInflater Service Provider da System Manager. Quindi potrebbe esserci una differenza di cucciolata nello stack di chiamate. – NguyenDat

+9

LayoutInflater.from (contesto) anche gettare errore se il gonfiatore non può essere retreived: qui il codice: LayoutInflater public static da (contesto Context) { LayoutInflater LayoutInflater = (LayoutInflater) context.getSystemService (Context.LAYOUT_INFLATER_SERVICE); if (LayoutInflater == null) { throw new AssertionError ("LayoutInflater not found."); } return LayoutInflater; } – Hiep

Problemi correlati