3

I have to do these kind of checks pretty often in my code and i wanted to know if there is a clean way of getting resources without having to write if statements to check for versions.

if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.LOLLIPOP) 
{
    imageView.setImageDrawable(getDrawable(R.drawable.ic_circled_v));
}
else
{
    imageView.setImageDrawable(getResources().getDrawable(R.drawable.ic_circled_v));
}
VIN
  • 4,721
  • 5
  • 26
  • 58
Dishonered
  • 6,544
  • 7
  • 23
  • 43
  • 2
    https://stackoverflow.com/questions/43087128/when-to-use-contextcompact-class – Killer May 26 '18 at 06:52
  • Good explanation here about the various compat options. https://stackoverflow.com/a/29146895/4138919 – VIN Aug 27 '18 at 18:30

2 Answers2

5

This is how you can obtain your drawable resource and maintain backward compatibility.

This is the code you want to use in your Activity:

imageView.setImageDrawable(ContextCompat.getDrawable(this, R.drawable.icon_heart_fill_red));

where icon_heart_fill_red is the name of your drawable.

VIN
  • 4,721
  • 5
  • 26
  • 58
Parth Patel
  • 871
  • 9
  • 21
1

use annotations, @requireApi or @targetApi

WeekL
  • 34
  • 5