programing

Android, 문자열에서 리소스 ID를 가져오고 있습니까?

prostudy 2022. 8. 1. 21:01
반응형

Android, 문자열에서 리소스 ID를 가져오고 있습니까?

클래스 중 하나의 메서드에 리소스 ID를 전달해야 합니다.참조가 가리키는 ID와 문자열이 모두 필요합니다.어떻게 하면 좋을까요?

예를 들어 다음과 같습니다.

R.drawable.icon

이것의 정수 ID를 가져와야 하지만 "icon" 문자열에도 액세스해야 합니다.

method에 전달해야 하는 것은 "icon" 문자열뿐이라면 더 좋습니다.

@EboMike: 몰랐네Resources.getIdentifier()존재했다.

프로젝트에서는 다음 코드를 사용하여 작업을 수행했습니다.

public static int getResId(String resName, Class<?> c) {

    try {
        Field idField = c.getDeclaredField(resName);
        return idField.getInt(idField);
    } catch (Exception e) {
        e.printStackTrace();
        return -1;
    } 
}

그것은 다음과 같이 사용될 것이다.R.drawable.icon자원 정수값

int resID = getResId("icon", R.drawable.class); // or other resource class

블로그에 올린 글 중에Resources.getIdentifier()저처럼 반성을 하는 것보다 느려요.이것 좀 봐봐요.

이 함수를 사용하여 리소스 ID를 가져올 수 있습니다.

public static int getResourceId(String pVariableName, String pResourcename, String pPackageName) 
{
    try {
        return getResources().getIdentifier(pVariableName, pResourcename, pPackageName);
    } catch (Exception e) {
        e.printStackTrace();
        return -1;
    } 
}

이와 같은 드로잉 가능한 콜 기능을 원하시면

getResourceId("myIcon", "drawable", getPackageName());

현악기 같은 경우에는 이렇게 부르면 돼요

getResourceId("myAppName", "string", getPackageName());

읽어주세요

이것은 @Macarse 응답에 기초하고 있습니다.

이를 통해 리소스 ID를 보다 빠르고 코드 친화적으로 가져올 수 있습니다.

public static int getId(String resourceName, Class<?> c) {
    try {
        Field idField = c.getDeclaredField(resourceName);
        return idField.getInt(idField);
    } catch (Exception e) {
        throw new RuntimeException("No resource ID found for: "
                + resourceName + " / " + c, e);
    }
}

예:

getId("icon", R.drawable.class);

리소스 이름에서 애플리케이션 리소스 ID를 가져오는 방법은 매우 일반적인 질문입니다.

리소스 이름에서 네이티브 Android 리소스 ID를 가져오는 방법에 대한 답변이 적습니다.다음은 리소스 이름별로 Android 그리기 가능한 리소스를 가져오는 솔루션입니다.

public static Drawable getAndroidDrawable(String pDrawableName){
    int resourceId=Resources.getSystem().getIdentifier(pDrawableName, "drawable", "android");
    if(resourceId==0){
        return null;
    } else {
        return Resources.getSystem().getDrawable(resourceId);
    }
}

메서드는 다른 유형의 리소스에 액세스하도록 수정할 수 있습니다.

문자열과 int를 조합해야 한다면 Map은 어떻습니까?

static Map<String, Integer> icons = new HashMap<String, Integer>();

static {
    icons.add("icon1", R.drawable.icon);
    icons.add("icon2", R.drawable.othericon);
    icons.add("someicon", R.drawable.whatever);
}

이렇게 하면 효과가 있습니다.

    imageView.setImageResource(context.getResources().
         getIdentifier("drawable/apple", null, context.getPackageName()));
Simple method to get resource ID:

public int getDrawableName(Context ctx,String str){
    return ctx.getResources().getIdentifier(str,"drawable",ctx.getPackageName());
}

사용할 수 있습니다.Resources.getIdentifier()단, XML 파일에서 사용할 때 문자열 형식을 사용해야 합니다.package:drawable/icon.

하나의 파라미터만 전달하고 어느 파라미터는 중요하지 않다고 했으므로 리소스 ID를 전달하고 문자열 이름을 검색할 수 있습니다.이렇게 하면 다음과 같습니다.

String name = getResources().getResourceEntryName(id);

이것이 두 값을 모두 얻는 가장 효율적인 방법일 수 있습니다.긴 끈에서 "아이콘" 부분만 찾느라 애쓸 필요는 없습니다.

문자열에서 리소스 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);

Kotlin 어프로치

inline fun <reified T: Class<*>> T.getId(resourceName: String): Int {
            return try {
                val idField = getDeclaredField (resourceName)
                idField.getInt(idField)
            } catch (e:Exception) {
                e.printStackTrace()
                -1
            }
        }

사용방법:

val resId = R.drawable::class.java.getId("icon")

또는 다음 중 하나를 선택합니다.

val resId = R.id::class.java.getId("viewId")

res/layout/my_image_layout.xml에서

<LinearLayout ...>
    <ImageView
        android:id="@+id/row_0_col_7"
      ...>
    </ImageView>
</LinearLayout>

ImageView를 @+id 값으로 취득하려면 Java 코드 내에서 다음 절차를 수행합니다.

String row = "0";
String column= "7";
String tileID = "row_" + (row) + "_col_" + (column);
ImageView image = (ImageView) activity.findViewById(activity.getResources()
                .getIdentifier(tileID, "id", activity.getPackageName()));

/*Bottom code changes that ImageView to a different image. "blank" (R.mipmap.blank) is the name of an image I have in my drawable folder. */
image.setImageResource(R.mipmap.blank);  

MonoDroid/Xamarin에서.Android의 특징:

 var resourceId = Resources.GetIdentifier("icon", "drawable", PackageName);

그러나 GetIdentifier는 Android에서는 권장되지 않으므로 다음과 같이 Reflection을 사용할 수 있습니다.

 var resourceId = (int)typeof(Resource.Drawable).GetField("icon").GetValue(null);

전달하고 있는 문자열을 try/catch 또는 검증하는 것이 좋습니다.

문자열 리소스 이름에서 Drawable id를 얻기 위해 다음 코드를 사용합니다.

private int getResId(String resName) {
    int defId = -1;
    try {
        Field f = R.drawable.class.getDeclaredField(resName);
        Field def = R.drawable.class.getDeclaredField("transparent_flag");
        defId = def.getInt(null);
        return f.getInt(null);
    } catch (NoSuchFieldException | IllegalAccessException e) {
        return defId;
    }
}

언급URL : https://stackoverflow.com/questions/4427608/android-getting-resource-id-from-string

반응형