简体   繁体   中英

Create a custom Drawable and use it in XML

I am busy creating a less complicated version of NinePatchDrawable that tiles the inner panels instead of stretching them.

I can implement the actual logic to do the rendering and such.

However, I can't find documentation about how to use this Drawable in the XML files. Is this possible? That is, can I have a <tileable-nine-patch> , or some such, tag I can use to define resources?

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.

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.

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">

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM