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.
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 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.
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.
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
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With