Android set XML shape as drawable programmatically

29,591

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
Share:
29,591

Related videos on Youtube

CQM
Author by

CQM

Updated on April 23, 2021

Comments

  • CQM
    CQM about 3 years

    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.

  • Melinda Green
    Melinda Green almost 11 years
    Pointing out the "R.drawable" namespace was key, thanks K-ballo!
  • Rahul Raina
    Rahul Raina about 8 years
    getDrawable(id) id now depricated.