Android set XML shape as drawable programmatically
Asked Answered
E

2

26

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.

Edulcorate answered 8/6, 2012 at 23:29 Comment(0)
R
47

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
Riverhead answered 8/6, 2012 at 23:30 Comment(2)
Pointing out the "R.drawable" namespace was key, thanks K-ballo!Wyly
getDrawable(id) id now depricated.Crumple
D
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://mcmap.net/q/53608/-android-getresources-getdrawable-deprecated-api-22

Darlinedarling answered 23/4, 2021 at 8:29 Comment(0)

© 2022 - 2024 — McMap. All rights reserved.