Android set XML shape as drawable programmatically Android set XML shape as drawable programmatically xml xml

Android set XML shape as drawable programmatically


You don't need to get the drawable yourself. Use this instead:

catAll.setBackgroundResource(R.drawable.myshape);

For future reference, if you do wish to get the drawable keep in mind that drawables live in the R.drawable namespace. So your code would became:

getResources().getDrawable(R.drawable.myshape);

This is akin to what you do in your XML:

@drawable/myshape

instead of

@id/myshape


The question is really old but googles first hit references to this thread.

So getDrawable(id) is deprecated.

Short solution (kotlin)

yourView.background = ContextCompat.getDrawable(context, R.drawable.your_ressource_id)

For more, please read this: https://stackoverflow.com/a/29146895/4420355