Java – Android : getDrawable and other resources without a version check?

Android : getDrawable and other resources without a version check?… here is a solution to the problem.

Android : getDrawable and other resources without a version check?

I

have to do such checks frequently in my code, and I’m wondering if there’s a clean way to get resources without writing an if statement to check the version.

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));
}

Solution

This is how you get drawable resources and maintain backward compatibility.

This is the code you want to use in the activity:

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

where icon_heart_fill_red is the name of your drawable.

Related Problems and Solutions