Drarig29
Drarig29

Reputation: 2245

Add custom border to view at runtime

I'd like to add a custom border to a listview item when selected, at runtime. But my current minSDK is 11 and I don't want to change it...

So I've created two drawables : custom_border and selected_custom_border.

Currently, I'm importing them using this :

v.setBackground(ContextCompat.getDrawable(MainActivity.this, R.drawable.custom_border));

But View.setBackground requires API level 16... is there an alternative for this method ?

Upvotes: 1

Views: 47

Answers (1)

Mattia Maestrini
Mattia Maestrini

Reputation: 32780

On device with API level lower than 16 you can use setBackgroundDrawable(Drawable).

For example:

Drawable drawable = ContextCompat.getDrawable(MainActivity.this, R.drawable.custom_border);

if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.JELLY_BEAN) {
    this.setBackground(drawable);
} else {
    this.setBackgroundDrawable(drawable);
}

Upvotes: 1

Related Questions