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

前端 未结 6 982
别跟我提以往
别跟我提以往 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 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);
    }
    

提交回复
热议问题