25

Hello I have a drawable myshape.xml, it contains a <shape> and I cannot set an android:id to shapes.

In my code I want to set the background of a view to this file using

catAll.setBackgroundDrawable(getResources().getDrawable(R.id......???));

where myshape.xml does not show up in my R file because it has no id. and I cannot set id to object.

In my XML I do set the shape by simply typing the drawable resource name. But I need to do this programmatically.

CQM
  • 36,672
  • 69
  • 214
  • 357

2 Answers2

44

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
K-ballo
  • 76,488
  • 19
  • 144
  • 164
0

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

kuzdu
  • 5,943
  • 1
  • 37
  • 56