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
  • 5,430
  • 6
  • 32
  • 67
Dishonered
  • 7,622
  • 7
  • 30
  • 49

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
  • 5,430
  • 6
  • 32
  • 67
Parth Patel
  • 935
  • 1
  • 11
  • 27
1

use annotations, @requireApi or @targetApi

WeekL
  • 34
  • 5