리소스 ID를 메소드에 전달해야 하지만 해당 문자열 리소스. 예를 들어, R.drawable.icon이 있고 정수 ID와 "icon" 문자열이 모두 필요합니다.
Resources.getIdentifier() 사용
한 가지 해결책은 Resources 클래스의 getIdentifier() 메서드를 사용하는 것입니다. 이 메소드는 문자열 리소스 이름과 리소스 유형(예: 드로어블)을 인수로 사용하고 연관된 정수 ID를 반환합니다.
// Get the integer ID for the icon int id = resources.getIdentifier("icon", "drawable", getPackageName()); // Retrieve the string resource String stringResource = resources.getString(id);
Reflection 사용
다른 옵션 리플렉션을 사용하여 리소스 ID 필드에 직접 액세스하는 것입니다. 이 솔루션은 코드/리소스 축소가 활성화된 릴리스 빌드에서는 작동하지 않을 수 있습니다.
// Get the R.drawable class Class<?> clazz = R.drawable.class; // Get the field for the icon resource Field idField = clazz.getDeclaredField("icon"); // Get the integer ID int id = idField.getInt(null); // Retrieve the string resource String stringResource = resources.getString(id);
두 접근 방식 결합
최대한의 유연성을 위해 두 접근 방식을 결합할 수 있습니다. . 문자열 리소스 이름을 메서드에 전달하고 메서드 내에서 선호하는 기술(reflection 또는 getIdentifier())을 사용하여 ID와 문자열을 검색합니다.
// Method that accepts the string resource name public void processResource(String resourceName) { // Get the R.drawable class Class<?> clazz = R.drawable.class; try { // Try using reflection to get the ID Field idField = clazz.getDeclaredField(resourceName); int id = idField.getInt(null); // Retrieve the string resource String stringResource = resources.getString(id); } catch (Exception e) { // Fallback to using getIdentifier() int id = resources.getIdentifier(resourceName, "drawable", getPackageName()); String stringResource = resources.getString(id); } // Use the ID and string as needed in your method ... }
위 내용은 Android 리소스 ID와 해당 문자열을 검색하는 방법은 무엇입니까?의 상세 내용입니다. 자세한 내용은 PHP 중국어 웹사이트의 기타 관련 기사를 참조하세요!