알려진 리소스 이름을 가진 리소스 ID를 가져오려면 어떻게 해야 합니까?
int ID가 아닌 이름으로 String이나 Drawable과 같은 리소스에 액세스하고 싶다.
어떤 방법으로 하면 좋을까요?
내가 제대로 이해했다면 이게 네가 원하는 거야
int drawableResourceId = this.getResources().getIdentifier("nameOfDrawable", "drawable", this.getPackageName());
여기서 "this"는 명확히 하기 위해 작성된 활동입니다.
strings.xml의 문자열 또는 UI 요소의 식별자를 원하는 경우 "drawable"로 대체합니다.
int resourceId = this.getResources().getIdentifier("nameOfResource", "id", this.getPackageName());
경고하는데, 이 방법은 매우 느려요. 필요한 곳만 사용하세요.
공식 문서 링크:Resources.getIdentifier(문자열 이름, 문자열 defType, 문자열 defPackage)
다음과 같습니다.
R.drawable.resourcename
이 기능을 가지고 있지 않은지 확인합니다.Android.R
Import된 네임스페이스는 Eclipse(사용 중인 경우)를 혼동할 수 있습니다.
이 방법으로 동작하지 않는 경우는, 항상 콘텍스트를 사용할 수 있습니다.getResources
메서드...
Drawable resImg = this.context.getResources().getDrawable(R.drawable.resource);
어디에this.context
로 이니셜이 되어 있다.Activity
,Service
또는 다른 것Context
서브클래스
업데이트:
원하는 이름이라면Resources
클래스(지정자)getResources()
)는getResourceName(int)
메서드 및 agetResourceTypeName(int)
?
업데이트 2:
그Resources
class에는 다음 메서드가 있습니다.
public int getIdentifier (String name, String defType, String defPackage)
지정된 리소스 이름 type & package의 정수를 반환합니다.
int resourceID =
this.getResources().getIdentifier("resource name", "resource type as mentioned in R.java",this.getPackageName());
•Kotlin Version
경유로Extension Function
Kotlin에서 리소스 ID를 찾으려면 아래 스니펫을 Kotlin 파일에 추가하십시오.
내선Functions.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
이제 컨텍스트 참조가 있는 모든 리소스 ID에 액세스할 수 있습니다.resIdByName
방법:
val drawableResId = context.resIdByName("ic_edit_black_24dp", "drawable")
val stringResId = context.resIdByName("title_home", "string")
.
.
.
문자열에서 리소스 ID를 가져오는 간단한 방법입니다.여기서 resourceName은 XML 파일에 포함된 그리기 가능한 폴더에 있는 리소스 ImageView의 이름입니다.
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);
// 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());
리소스 ID를 얻기 위해 내 방법을 사용하는 것이 좋습니다.속도가 느린 getIdentidier() 메서드를 사용하는 것보다 훨씬 효율적입니다.
코드는 다음과 같습니다.
/**
* @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;
}
코틀린에서는, 다음의 조작이 유효합니다.
val id = resources.getIdentifier("your_resource_name", "drawable", context?.getPackageName())
리소스가 mipmap 폴더에 있는 경우 "drawable" 대신 "mipmap" 매개 변수를 사용할 수 있습니다.
나는 이 수업이 자원을 가지고 다루는데 매우 도움이 된다는 것을 알았다.여기에는 다음과 같이 치수, 색상, 도면 및 문자열을 처리하는 몇 가지 정의된 방법이 있습니다.
public static String getString(Context context, String stringId) {
int sid = getStringId(context, stringId);
if (sid > 0) {
return context.getResources().getString(sid);
} else {
return "";
}
}
@lonkly 솔루션과 함께
- 반사 및 현장 접근성 보기
- 불필요한 변수
방법:
/**
* 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());
}
}
언급URL : https://stackoverflow.com/questions/3476430/how-to-get-a-resource-id-with-a-known-resource-name
'programing' 카테고리의 다른 글
vuelidate 참/거짓 확인 (0) | 2022.06.04 |
---|---|
java.util을 변환합니다.java.time 날짜로컬 날짜 (0) | 2022.06.04 |
난독화 C코드 콘테스트 2006.sykes 2.c에 대해 설명해 주세요. (0) | 2022.06.04 |
[Vue.js] Vuex에서의 네임스페이스 (0) | 2022.06.04 |
C에서 _start()의 용도는 무엇입니까? (0) | 2022.06.04 |