2010-08-13 26 views
130

Desidero accedere a una risorsa come String o Drawable in base al nome e non al suo int id.Come ottenere un ID risorsa con un nome di risorsa noto?

Quale metodo dovrei usare per questo?

+1

possibile duplicato di [Come posso ottenere l'ID risorsa di un'immagine se conosco il suo nome?] (Http://stackoverflow.com/questions/3042961/how-can-i-get-the-resource-id- of-an-image-if-i-know-its-name) – ghoti

risposta

116

Sarà qualcosa di simile:

R.drawable.resourcename

Assicurarsi che non si dispone di spazio dei nomi Android.R importato come si può confondere Eclipse (se è ciò che si sta utilizzando).

Se questo non funziona, si può sempre usare il metodo di un contesto getResources ...

Drawable resImg = this.context.getResources().getDrawable(R.drawable.resource); 

Dove this.context è intialised come Activity, Service o qualsiasi altro Context sottoclasse.

Aggiornamento:

Se è il nome che si desidera, la classe Resources (restituito da getResources()) ha un metodo getResourceName(int), e un getResourceTypeName(int)?

Update 2:

La classe Resources ha questo metodo:

public int getIdentifier (String name, String defType, String defPackage) 

che restituisce il numero intero del nome della risorsa specificata, tipo & pacchetto.

+0

Thankq per la tua risposta .R.drawable.resourcename che sto usando ora ho bisogno di ottenere il suo valore intero passando resourcename – Aswan

+1

'R.drawable.resourcename' * è * il numero intero. – Rabid

+0

Ciao Rabid. Cosa hai detto è possibile accedere al valore di R.Drawable restituendo risorsa – Aswan

268

se ho capito bene, questo è ciò che si vuole

int drawableResourceId = this.getResources().getIdentifier("nameOfDrawable", "drawable", this.getPackageName()); 

Dove "questo" è un attività, scritto solo per chiarire.

Nel caso in cui si desidera una stringa in strings.xml o un identificatore di un elemento dell'interfaccia utente, sostituire "disegnabile"

int resourceId = this.getResources().getIdentifier("nameOfResource", "id", this.getPackageName()); 

Vi avverto, questo modo di ottenere identificatori è molto lento, utilizzare solo dove necessario .

link di documentazione ufficiale: Resources.getIdentifier(String name, String defType, String defPackage)

+2

Questo è piuttosto utile nel contesto della scrittura di test per assicurarsi che certe stringhe esistano o ecc. –

+0

Non conosco uomo, I Ho aggiunto un log prima e dopo getIdentifier() con timestamp e mi ha mostrato che viene eseguito in 0 - 1 ms! Quindi non è lento, è super veloce! Lo sto usando per ottenere immagini da risorse e funziona perfettamente. Testato su Nexus5x. –

6

vorrei suggerire di usare il mio metodo per ottenere un ID di risorsa. È molto più efficiente dell'utilizzo del metodo getIdentidier(), che è lento.

Ecco il codice:

/** 
* @author Lonkly 
* @param variableName - name of drawable, e.g R.drawable.<b>image</b> 
* @param с - class of resource, e.g R.drawable.class or R.raw.class 
* @return integer id of resource 
*/ 
public static int getResId(String variableName, Class<?> с) { 

    Field field = null; 
    int resId = 0; 
    try { 
     field = с.getField(variableName); 
     try { 
      resId = field.getInt(null); 
     } catch (Exception e) { 
      e.printStackTrace(); 
     } 
    } catch (Exception e) { 
     e.printStackTrace(); 
    } 
    return resId; 

} 
+0

Non funzionerà per tutti i casi. Ad esempio, se hai contenuto rispetto alla classe R.string avrà un campo stringa_name. E il tuo metodo non funzionerà in questo punto. – ddmytrenko

+2

Anche il tuo metodo non è veloce in realtà. Perché la serializzazione della classe Java non funziona mai in fretta. – ddmytrenko

22
int resourceID = 
    this.getResources().getIdentifier("resource name", "resource type as mentioned in R.java",this.getPackageName()); 
+4

Sarebbe ancora meglio se spiegassi il codice che hai postato. –

9

Un modo semplice per ottenere ID di risorsa da stringa. Qui resourceName è il nome della risorsa ImageView nella cartella drawable che è inclusa anche nel file XML.

int resID = getResources().getIdentifier(resourceName, "id", getPackageName()); 
ImageView im = (ImageView) findViewById(resID); 
Context context = im.getContext(); 
int id = context.getResources().getIdentifier(resourceName, "drawable", 
context.getPackageName()); 
im.setImageResource(id); 
0

Ho trovato this class molto utile da gestire con le risorse.Ha alcuni metodi per affrontare Dimens, colori, drawable e stringhe definiti, come questo:

public static String getString(Context context, String stringId) { 
    int sid = getStringId(context, stringId); 
    if (sid > 0) { 
     return context.getResources().getString(sid); 
    } else { 
     return ""; 
    } 
} 
0

oltre a @lonkly soluzione

  1. vedono riflessi e campo dell'accessibilità
  2. variabili inutili

metodo:

/** 
* lookup a resource id by field name in static R.class 
* 
* @author - ceph3us 
* @param variableName - name of drawable, e.g R.drawable.<b>image</b> 
* @param с   - class of resource, e.g R.drawable.class or R.raw.class 
* @return integer id of resource 
*/ 
public static int getResId(String variableName, Class<?> с) 
        throws android.content.res.Resources.NotFoundException { 
    try { 
     // lookup field in class 
     java.lang.reflect.Field field = с.getField(variableName); 
     // always set access when using reflections 
     // preventing IllegalAccessException 
     field.setAccessible(true); 
     // we can use here also Field.get() and do a cast 
     // receiver reference is null as it's static field 
     return field.getInt(null); 
    } catch (Exception e) { 
     // rethrow as not found ex 
     throw new Resources.NotFoundException(e.getMessage()); 
    } 
} 
Problemi correlati