我需要获取一个Drawable对象以显示在图像按钮上。是否有一种方法可以使用类似下面的代码(或类似的代码)从android.R.drawable.*包中获取一个对象?
例如,如果drawableId是android.R.drawable.ic_delete
mContext.getResources().getDrawable(drawableId)
我需要获取一个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);
getDrawable(int, Theme)
方法替代getDrawable(int)
方法,因为它允许你获取与给定屏幕密度/主题
相关联的特定资源ID
的drawable
对象。调用已过时的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);
}
context.getDrawable(id);
seems to be equivalent to resources.getDrawable(id, context.getTheme());
- ErickBergmannResourcesCompat.getDrawable(resources, id, context.getTheme());
- k2col自API 21起,您也可以使用:
ResourcesCompat.getDrawable(getResources(), R.drawable.name, null);
使用 ContextCompat.getDrawable(context, android.R.drawable.ic_dialog_email)
代替。
现在您需要使用
ResourcesCompat.getDrawable(context.getResources(), R.drawable.img_user, null)
import android.content.Context
import android.graphics.drawable.Drawable
import androidx.core.content.res.ResourcesCompat
object ResourceUtils {
fun getColor(context: Context, color: Int): Int {
return ResourcesCompat.getColor(context.resources, color, null)
}
fun getDrawable(context: Context, drawable: Int): Drawable? {
return ResourcesCompat.getDrawable(context.resources, drawable, null)
}
}
使用方法如下:
Drawable img=ResourceUtils.getDrawable(context, R.drawable.img_user)
image.setImageDrawable(img);
button.setBackgroundResource(android.R.drawable.ic_delete);
或者使用以下代码设置Drawable left,top,right,bottom。在这种情况下,我正在设置drawable left。
int imgResource = R.drawable.left_img;
button.setCompoundDrawablesWithIntrinsicBounds(imgResource, 0, 0, 0);
并且
getResources().getDrawable()
现在已经被弃用
针对Kotlin程序员的解决方案(使用API 22及以上版本)
val res = context?.let { ContextCompat.getDrawable(it, R.id.any_resource }
getDrawable(int id)
方法已被弃用。请改用getDrawable(int id, Resources.Theme theme)
方法。可以使用getTheme()
方法进行帮助。 - Isaac Zais