我需要一个 Drawable 对象以显示在图像按钮上。有没有办法使用下面的代码(或类似的代码)从 android.R.drawable.* 包中获取对象?
例如,如果 drawableId 是 android.R.drawable.ic_delete
mContext.getResources().getDrawable(drawableId)
原文由 Blaskovicz 发布,翻译遵循 CC BY-SA 4.0 许可协议
我需要一个 Drawable 对象以显示在图像按钮上。有没有办法使用下面的代码(或类似的代码)从 android.R.drawable.* 包中获取对象?
例如,如果 drawableId 是 android.R.drawable.ic_delete
mContext.getResources().getDrawable(drawableId)
原文由 Blaskovicz 发布,翻译遵循 CC BY-SA 4.0 许可协议
所以现在你需要使用
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);
原文由 Sanjayrajsinh 发布,翻译遵循 CC BY-SA 4.0 许可协议
2 回答1.3k 阅读✓ 已解决
2 回答2.7k 阅读
2 回答1.7k 阅读
1 回答2.1k 阅读
1 回答1.2k 阅读
1 回答1.2k 阅读
1 回答580 阅读✓ 已解决