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

前端 未结 6 963
别跟我提以往
别跟我提以往 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条回答
  • 2020-12-12 15:56
    Drawable d = getResources().getDrawable(android.R.drawable.ic_dialog_email);
    ImageView image = (ImageView)findViewById(R.id.image);
    image.setImageDrawable(d);
    
    0 讨论(0)
  • 2020-12-12 15:57

    Following a solution for Kotlin programmers (from API 22)

    val res = context?.let { ContextCompat.getDrawable(it, R.id.any_resource }
    
    0 讨论(0)
  • 2020-12-12 16:01

    As of API 21, you could also use:

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

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

    0 讨论(0)
  • 2020-12-12 16:05

    As of API 21, you should use the getDrawable(int, Theme) method instead of getDrawable(int), as it allows you to fetch a drawable object associated with a particular resource ID for the given screen density/theme. Calling the deprecated getDrawable(int) method is equivalent to calling getDrawable(int, null).

    You should use the following code from the support library instead:

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

    Using this method is equivalent to calling:

    if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.LOLLIPOP) {
        return resources.getDrawable(id, context.getTheme());
    } else {
        return resources.getDrawable(id);
    }
    
    0 讨论(0)
  • 2020-12-12 16:05

    best way is

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

    OR this for Drawable left and something like that for right etc.

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

    and

    getResources().getDrawable() is now deprecated

    0 讨论(0)
  • 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);
    
    0 讨论(0)
提交回复
热议问题