Jak uzyskać identyfikator zasobu o znanej nazwie zasobu?

Chcę uzyskać dostęp do zasobu, takiego jak ciąg znaków lub Drawable po jego nazwie, a nie po jego id int.

Jaką metodę bym do tego użył?

Author: Kuya, 2010-08-13

10 answers

Będzie to coś w stylu:

R.drawable.resourcename

Upewnij się, że nie masz zaimportowanej przestrzeni nazw Android.R, ponieważ może to mylić Eclipse (jeśli tego właśnie używasz).

Jeśli to nie zadziała, zawsze możesz użyć metody getResources kontekstu ...

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

Gdzie this.context jest intializowana jako Activity, Service lub jakąkolwiek inną Context podklasę.

Update:

Jeśli jest to nazwa, którą chcesz, Klasa Resources (zwracana przez getResources()) ma metodę getResourceName(int), a getResourceTypeName(int)?

Aktualizacja 2:

Klasa Resources ma następującą metodę:

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

Który zwraca liczbę całkowitą podanej nazwy zasobu, typu i pakietu.

 151
Author: Rabid,
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/doraprojects.net/template/agent.layouts/content.php on line 54
2019-05-05 14:39:35

If I understand right, this is what you want

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

Gdzie "to" jest działaniem, napisanym tylko dla wyjaśnienia.

W przypadku, gdy chcesz ciąg w ciągach.xml lub identyfikator elementu UI, zamiennik "drawable"

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

Ostrzegam, ten sposób uzyskiwania identyfikatorów jest bardzo powolny, używać tylko tam, gdzie jest to potrzebne.

Link do oficjalnej dokumentacji: zasoby.getIdentifier (String name, String defType, String defPackage)

 352
Author: Maragues,
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/doraprojects.net/template/agent.layouts/content.php on line 54
2017-04-12 13:08:29
int resourceID = 
    this.getResources().getIdentifier("resource name", "resource type as mentioned in R.java",this.getPackageName());
 25
Author: user1393422,
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/doraprojects.net/template/agent.layouts/content.php on line 54
2012-05-14 19:27:47

Kotlin Version via Extension Function

Aby znaleźć identyfikator zasobu według jego nazwy w Kotlinie, dodaj poniższy fragment w pliku kotlin:

Rozszerzenie funkcji.kt

import android.content.Context
import android.content.res.Resources

fun Context.resIdByName(resIdName: String?, resType: String): Int {
    resIdName?.let {
        return resources.getIdentifier(it, resType, packageName)
    }
    throw Resources.NotFoundException()
}


Usage

Teraz wszystkie identyfikatory zasobów są dostępne wszędzie tam, gdzie masz odniesienie do kontekstu za pomocą metody resIdByName:

val drawableResId = context.resIdByName("ic_edit_black_24dp", "drawable")
val stringResId = context.resIdByName("title_home", "string")
.
.
.    
 18
Author: aminography,
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/doraprojects.net/template/agent.layouts/content.php on line 54
2019-06-19 10:31:55

Prosty sposób na uzyskanie identyfikatora zasobu z łańcucha znaków. Tutaj resourceName jest nazwą zasobu ImageView w folderze drawable, który jest również zawarty w pliku 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);
 15
Author: Muhammad Adil,
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/doraprojects.net/template/agent.layouts/content.php on line 54
2016-09-06 17:09:39

Sugerowałbym użycie mojej metody, aby uzyskać identyfikator zasobu. Jest o wiele bardziej wydajna niż metoda getIdentidier (), która jest powolna.

Oto kod:

/**
 * @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;

}
 6
Author: Lonkly,
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/doraprojects.net/template/agent.layouts/content.php on line 54
2016-09-06 17:09:49
// image from res/drawable
    int resID = getResources().getIdentifier("my_image", 
            "drawable", getPackageName());
// view
    int resID = getResources().getIdentifier("my_resource", 
            "id", getPackageName());

// string
    int resID = getResources().getIdentifier("my_string", 
            "string", getPackageName());
 6
Author: Manthan Patel,
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/doraprojects.net/template/agent.layouts/content.php on line 54
2019-08-01 08:11:52

W Kotlinie działa mi dobrze:

val id = resources.getIdentifier("your_resource_name", "drawable", context?.getPackageName())

Jeśli zasób znajduje się w folderze mipmap, możesz użyć parametru "mipmap" zamiast "drawable".

 1
Author: Jens van de Mötter,
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/doraprojects.net/template/agent.layouts/content.php on line 54
2020-06-06 09:49:07

Znalazłem Ta klasa bardzo pomocna w obsłudze zasobów. Ma kilka zdefiniowanych metod radzenia sobie z dimenami, kolorami, rysunkami i ciągami, takich jak ta: {]}

public static String getString(Context context, String stringId) {
    int sid = getStringId(context, stringId);
    if (sid > 0) {
        return context.getResources().getString(sid);
    } else {
        return "";
    }
}
 0
Author: Diego Malone,
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/doraprojects.net/template/agent.layouts/content.php on line 54
2016-06-30 15:27:15

Oprócz @lonkly solution

  1. Zobacz odbicia i dostępność pola
  2. niepotrzebne zmienne

Metoda:

/**
 * 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());
    }
}
 0
Author: ceph3us,
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/doraprojects.net/template/agent.layouts/content.php on line 54
2017-06-27 15:15:39