How do you obtain a Drawable object from a resource id in android package?

前端 未结 6 987
别跟我提以往
别跟我提以往 2020-12-12 15:18

I need to get a Drawable object to display on an image button. Is there a way to use the code below (or something like it) to get an object from the android.R.drawable.* pac

6条回答
  •  Happy的楠姐
    2020-12-12 16:07

    From API 21 getDrawable(int id) is deprecated. So now you need to use

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

    But Best way to do is : You should create one common class for get drawable and colors because if any thing change or deprecate in future then you no need to change everywhere in your project.You just change in this method

    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)
        }
    }
    

    use this method like :

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

提交回复
热议问题