Search code examples
androiddrawablexml-drawablelayer-list

Possible to create a fixed-width drawable in XML?


I'm trying to simplify some graphics from requiring a 9-patch for each density, to just using an XML drawable. It's a fairly simple graphic:

9-patch drawable

2 Segments:

  • 8dp wide for both segments
  • Top segment is 2dp tall
  • Bottom segment fills the view
  • Right side is filled with transparency

Giving this result when set as a background image:

9-patch as list item example

It seems like this should be fairly simple to recreate as an XML drawable, and would avoid creating 5 different 9-patch graphics. However, I've looked into layer-list drawables, inset drawables, clip drawables -- they all seem to require that you know the size of the view beforehand (e.g. to keep it 2dp for an inset, you'd need to set insetRight to the width of the view - 2dp). I also tried using the shape tag's size tag, but that doesn't keep a fixed size, just a fixed proportion (so for taller views it will scale proportionally).

Am I overlooking something simple, or is this something I'd have to resort to checking programatically after layout?


Solution

  • This is not possible. This is the best solution I found. Only xml, no coding, no bitmaps, no additional views )

    <layer-list xmlns:android="http://schemas.android.com/apk/res/android">
    <item>
        <shape
            xmlns:android="http://schemas.android.com/apk/res/android"
            android:shape="rectangle">
    
            <solid
                android:color="#ff0000" />
        </shape>
    </item>
    <item
        android:top="4dp">
        <shape
            xmlns:android="http://schemas.android.com/apk/res/android"
            android:shape="rectangle">
    
            <solid
                android:color="#00ff00" />
        </shape>
    </item>
    
    <item
        android:left="10dp">
        <shape
            android:shape="rectangle">
            <solid
                android:color="#FFFFFF" />
        </shape>
    </item> 
    </layer-list>
    

    enter image description here

    Via code you can make your own drawble type with desired behavior. Xml drawable very limited. IMHO my suggestion is the closest to what you demanded.