In Android API level 22 and above, the method getResources().getDrawable()
has been marked as deprecated. The recommended alternative is simply to use getDrawable()
directly. What are the specific changes that led to this update?
In API 22, getResources().getDrawable()
was deprecated due to its lack of theme support. It's replaced by ContextCompat.getDrawable()
in support libraries for backward compatibility, allowing you to pass a context with theme info.
Drawable drawable = ContextCompat.getDrawable(context, R.drawable.your_drawable);
The deprecation of getResources().getDrawable()
in Android API 22 was primarily a move to improve theme-based resource retrieval. Prior to API 22, this method did not account for the current theme, which could lead to inconsistencies when using drawable resources with theme-dependent attributes.
Starting from API 21, which introduced material design, theming became more integral to Android development. To enhance this, getDrawable(int id, Theme theme)
was introduced, allowing developers to provide a specific theme when retrieving resources, ensuring consistency in how drawables are displayed across different themes.
For backward compatibility, especially with pre-API 22 versions, developers should use ContextCompat.getDrawable()
:
Drawable drawable = ContextCompat.getDrawable(context, R.drawable.your_drawable);
This approach ties in theme information and ensures your drawable resources render consistently across various API levels. The move to deprecate the older getDrawable
method encourages developers to adopt these practices for better visual consistency in their applications.
In Android API 22, getResources().getDrawable()
got deprecated because it couldn't handle themes properly, especially with API 21 introducing Material Design. Now, use getDrawable(int id, Theme theme)
for theme support.
For backward compatibility, stick to ContextCompat.getDrawable()
:
Drawable drawable = ContextCompat.getDrawable(context, R.drawable.your_drawable);
This ensures your app renders drawable resources consistently across different Android versions.