Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Android set XML shape as drawable programmatically

Tags:

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.

like image 877
CQM Avatar asked Jun 08 '12 23:06

CQM


People also ask

How to set image in drawable XML android?

To use an image resource, add your file to the res/drawable/ directory of your project. Once in your project, you can reference the image resource from your code or your XML layout. Either way, it's referred to using a resource ID, which is the file name without the file type extension. For example, refer to my_image.

How do you make a drawable shape?

How to Create and Use a Shape Drawable. Creating shape drawables is done in XML with the <item> and <shape> elements. The <item> element is the enclosing parent of <shape> . It defines attributes like the width and height of the shape, but that is possible only if your project is API 23 and above.

How to add image drawable android?

Drag and drop your images directly onto the Resource Manager window in Android Studio. Alternatively, you can click the plus icon (+), choose Import Drawables, as shown in figure 3, and then select the files and folders that you want to import. Figure 3: Select Import Drawables from the dropdown menu.


1 Answers

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 
like image 187
K-ballo Avatar answered Oct 17 '22 04:10

K-ballo