Create a custom Drawable and use it in XML
Unfortunately it is not possible to use custom drawables in XML files (for API 23 and below) due to potential security issues. See here for a Google Groups thread about this very topic with a response from Romain Guy, one of the Android developers.
You can still use them in your Java code though.
Update:
As LeoFarage points out in the comments, starting in API 24 you can now use custom drawables in XML files but only within your application package.
Too late, but since there is no clear answer here what I tried. As @Casabancais answer copied from Android docs.
Create a drawable xml named say custom_drawable.xml with this
<?xml version="1.0" encoding="utf-8"?>
<drawable xmlns:android="http://schemas.android.com/apk/res/android"
class="com.my.package.path.MyCustomDrawable"
android:color="#ffff0000" />
com.mypackage.MyCustomDrawable.java
should be your java drawable class
Then you can use it in lets say background
tag for any xml like this
<androidx.constraintlayout.widget.ConstraintLayout
android:layout_width="match_parent"
android:background="@drawable/custom_drawable"
android:layout_height="wrap_content">
Starting Android API 24, custom Drawables classes can be used in XML only within your package.
Custom drawables classes may be used in XML in multiple ways:
Using the fully-qualified class name as the XML element name. For this method, the custom drawable class must be a public top-level class.
<com.yourapp.MyCustomDrawable
xmlns:android="http://schemas.android.com/apk/res/android"
android:color="#ffff0000"/>
Using drawable as the XML element name and specifying the fully-qualified class name from the class attribute. This method may be used for both public top-level classes and public static inner classes.
<drawable xmlns:android="http://schemas.android.com/apk/res/android"
class="com.myapp.MyTopLevelClass$InnerCustomDrawable"
android:color="#ffff0000" />
Note: that is not supported by support library.