Nice programing

Android에서 이름으로 드로어 블 리소스에 액세스하는 방법

nicepro 2020. 11. 19. 22:01
반응형

Android에서 이름으로 드로어 블 리소스에 액세스하는 방법


내 응용 프로그램에서 참조를 유지하고 싶지 않은 어딘가에 비트 맵 드로어 블을 가져와야합니다 R. 그래서 DrawableManager드로어 블을 관리 하는 클래스 만듭니다 .

public class DrawableManager {
    private static Context context = null;

    public static void init(Context c) {
        context = c;
    }

    public static Drawable getDrawable(String name) {
        return R.drawable.?
    }
}

그런 다음 다음과 같은 이름으로 드로어 블을 얻고 싶습니다 (car.png는 res / drawables 안에 있습니다).

Drawable d= DrawableManager.getDrawable("car.png");

그러나 보시다시피 이름으로 리소스에 액세스 할 수 없습니다.

public static Drawable getDrawable(String name) {
    return R.drawable.?
}

대안이 있습니까?


당신의 접근 방식은 거의 항상 잘못된 방법입니다 ( Context어딘가에 정적을 유지하는 것보다 드로어 블을 사용하는 객체 자체에 컨텍스트를 전달하는 것이 더 좋습니다 ).

이를 감안할 때 동적 드로어 블로드를 수행하려면 getIdentifier 를 사용할 수 있습니다 .

Resources resources = context.getResources();
final int resourceId = resources.getIdentifier(name, "drawable", 
   context.getPackageName());
return resources.getDrawable(resourceId);

이런 식으로 할 수 있습니다 .-

public static Drawable getDrawable(String name) {
    Context context = YourApplication.getContext();
    int resourceId = context.getResources().getIdentifier(name, "drawable", YourApplication.getContext().getPackageName());
    return context.getResources().getDrawable(resourceId);
}

어디서든 컨텍스트에 액세스하기 위해 Application 클래스를 확장 할 수 있습니다.

public class YourApplication extends Application {

    private static YourApplication instance;

    public YourApplication() {
        instance = this;
    }

    public static Context getContext() {
        return instance;
    }
}

Manifest application태그에 매핑하세요.

<application
    android:name=".YourApplication"
    ....

이미지 내용 수정 :

    ImageView image = (ImageView)view.findViewById(R.id.imagenElement);
    int resourceImage = activity.getResources().getIdentifier(element.getImageName(), "drawable", activity.getPackageName());
    image.setImageResource(resourceImage);

참고 URL : https://stackoverflow.com/questions/16369814/how-to-access-the-drawable-resources-by-name-in-android

반응형