Chcę uzyskać dostęp do zasobu, takiego jak String lub Drawable, według jego nazwy, a nie identyfikatora int.
Której metody użyłbym do tego?
Chcę uzyskać dostęp do zasobu, takiego jak String lub Drawable, według jego nazwy, a nie identyfikatora int.
Której metody użyłbym do tego?
Odpowiedzi:
Będzie to coś takiego:
R.drawable.resourcename
Upewnij się, że nie masz Android.Rzaimportowanej przestrzeni nazw, ponieważ może to zmylić Eclipse (jeśli tego właśnie używasz).
Jeśli to nie zadziała, zawsze możesz użyć getResourcesmetody kontekstu ...
Drawable resImg = this.context.getResources().getDrawable(R.drawable.resource);
Gdzie this.contextjest intialised jako Activity, Servicelub jakiekolwiek inne Contextpodklasy.
Aktualizacja:
Jeśli jest to żądana nazwa, Resourcesklasa (zwracana przez getResources()) ma getResourceName(int)metodę i znak getResourceTypeName(int)?
Aktualizacja 2 :
ResourcesKlasa ma tę metodę:
public int getIdentifier (String name, String defType, String defPackage)
Która zwraca liczbę całkowitą określonej nazwy zasobu, wpisz & pakiet.
R.drawable.resourcename jest liczbą całkowitą.
Jeśli dobrze zrozumiałem, tego właśnie chcesz
int drawableResourceId = this.getResources().getIdentifier("nameOfDrawable", "drawable", this.getPackageName());
Gdzie „to” jest działaniem, napisanym tylko w celu wyjaśnienia.
Jeśli chcesz mieć ciąg w strings.xml lub identyfikator elementu UI, zastąp „drawable”
int resourceId = this.getResources().getIdentifier("nameOfResource", "id", this.getPackageName());
Ostrzegam, ten sposób uzyskiwania identyfikatorów jest naprawdę powolny, używaj tylko w razie potrzeby.
Link do oficjalnej dokumentacji: Resources.getIdentifier (String name, String defType, String defPackage)
int resourceID =
this.getResources().getIdentifier("resource name", "resource type as mentioned in R.java",this.getPackageName());
Kotlin VersionprzezExtension FunctionAby znaleźć identyfikator zasobu według jego nazwy W Kotlin, dodaj poniższy fragment kodu w pliku kotlin:
ExtensionFunctions.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()
}
UsageTeraz wszystkie identyfikatory zasobów są dostępne wszędzie tam, gdzie masz odwołanie do kontekstu przy użyciu resIdByNamemetody:
val drawableResId = context.resIdByName("ic_edit_black_24dp", "drawable")
val stringResId = context.resIdByName("title_home", "string")
.
.
.
Prosty sposób na uzyskanie identyfikatora zasobu z ciągu. Tutaj nazwa_zasobu jest nazwą zasobu ImageView w folderze do rysowania, 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);
Sugerowałbym użycie mojej metody, aby uzyskać identyfikator zasobu. Jest to o wiele bardziej wydajne niż użycie metody getIdentidier (), która jest wolna.
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;
}
// 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());
Uważam, że ta klasa jest bardzo pomocna w zarządzaniu zasobami. Ma kilka zdefiniowanych metod radzenia sobie z wymiarami, kolorami, rysunkami i ciągami, takimi jak ten:
public static String getString(Context context, String stringId) {
int sid = getStringId(context, stringId);
if (sid > 0) {
return context.getResources().getString(sid);
} else {
return "";
}
}
oprócz rozwiązania @lonkly
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());
}
}
W Kotlinie działa dla mnie dobrze:
val id = resources.getIdentifier("your_resource_name", "drawable", context?.getPackageName())
Jeśli zasób jest umieszczony w folderze mipmap, możesz użyć parametru „mipmap” zamiast „drawable”.