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
  • 6,385
  • 7
  • 38
  • 77
Dishonered
  • 8,449
  • 9
  • 37
  • 50

2 Answers2

4

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
  • 6,385
  • 7
  • 38
  • 77
Parth Patel
  • 859
  • 2
  • 11
  • 28
1

use annotations, @requireApi or @targetApi

WeekL
  • 34
  • 5