[android] 안드로이드 패키지의 리소스 ID에서 Drawable 객체를 어떻게 얻습니까?

이미지 버튼에 Drawable 객체를 표시해야합니다. android.R.drawable. * 패키지에서 객체를 가져 오기 위해 아래의 코드를 사용하는 방법이 있습니까?

예를 들어 drawableId가 android.R.drawable.ic_delete 인 경우

mContext.getResources().getDrawable(drawableId)



답변

Drawable d = getResources().getDrawable(android.R.drawable.ic_dialog_email);
ImageView image = (ImageView)findViewById(R.id.image);
image.setImageDrawable(d);


답변

현재 API (21) , 당신은 사용해야하는 getDrawable(int, Theme)대신 방법을 getDrawable(int)당신이 가져올 수로, drawable특정과 관련된 객체 resource ID주어진를 들어 screen density/theme. deprecated getDrawable(int)메소드 호출은 호출과 동일합니다 getDrawable(int, null).

대신 지원 라이브러리에서 다음 코드를 사용해야합니다.

ContextCompat.getDrawable(context, android.R.drawable.ic_dialog_email)

이 메소드를 사용하는 것은 다음을 호출하는 것과 같습니다.

if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.LOLLIPOP) {
    return resources.getDrawable(id, context.getTheme());
} else {
    return resources.getDrawable(id);
}


답변

API 21부터 다음을 사용할 수도 있습니다.

   ResourcesCompat.getDrawable(getResources(), R.drawable.name, null);

대신에 ContextCompat.getDrawable(context, android.R.drawable.ic_dialog_email)


답변

가장 좋은 방법은

 button.setBackgroundResource(android.R.drawable.ic_delete);

또는 Drawable left의 경우 오른쪽과 같은 것입니다.

int imgResource = R.drawable.left_img;
button.setCompoundDrawablesWithIntrinsicBounds(imgResource, 0, 0, 0);

getResources().getDrawable() 더 이상 사용되지 않습니다


답변

API 21부터는 getDrawable(int id)더 이상 사용되지 않습니다. 이제는

ResourcesCompat.getDrawable(context.getResources(), R.drawable.img_user, null)

그러나 최선의 방법은 다음과 같습니다. 드로어 블과 색상을 얻기 위해 하나의 공통 클래스를 만들어야합니다. 앞으로 변경되거나 더 이상 사용되지 않는 경우 프로젝트의 모든 곳에서 변경할 필요가 없으므로이 방법을 변경하면됩니다.

object ResourceUtils {
    fun getColor(context: Context, color: Int): Int {
        return ResourcesCompat.getColor(context.getResources(), color, null)
    }

    fun getDrawable(context: Context, drawable: Int): Drawable? {
        return ResourcesCompat.getDrawable(context.getResources(), drawable, null)
    }
}

이 방법을 다음과 같이 사용하십시오.

Drawable img=ResourceUtils.getDrawable(context, R.drawable.img_user)
image.setImageDrawable(img);


답변

Kotlin 프로그래머를위한 솔루션 따르기 (API 22부터)

val res = context?.let { ContextCompat.getDrawable(it, R.id.any_resource }


답변