How do I make a drawable from multiple images?

21,862

After some trial-and-error, I was able to solve the problem in a satisfactory way. I simply implemented a Layer-List drawable as follows:

<?xml version="1.0" encoding="utf-8"?>
<layer-list
    xmlns:android="http://schemas.android.com/apk/res/android" >
    <item android:drawable="@drawable/btn_left" android:left="0px" />
    <item android:drawable="@drawable/btn_middle" 
        android:left="26px" android:right="26px" />
    <item android:drawable="@drawable/btn_right" android:right="0px" />
</layer-list>

Where the 26px values are the width of the two button side images in pixels.

To use this drawable, simply call it like any other drawable:

<bitmap android:src="@drawable/button_background" />

This works exactly how you would expect it to, with the middle expanding as normal to fit the desired width, and all three images expanding to fit the desired height. I hope others can benefit from this!

Share:
21,862

Related videos on Youtube

howettl
Author by

howettl

I am a professional mobile software developer living in Vancouver BC. I graduated from the University of Victoria with a B Sc in Computer Science.

Updated on July 09, 2022

Comments

  • howettl
    howettl almost 2 years

    I have three 9-patch PNG's which together make up the background for a button (left side, middle, right side). I would like to combine these three images together in a drawable which I can specify as the background for a button in XML, something along the lines of:

    res/drawable/button_background.xml:

    <?xml version="1.0" encoding="utf-8"?>
    <nine-patch xmlns:android="http://schemas.android.com/apk/res/android"
    android:src="@drawable/button_left_side" />
    
    <nine-patch android:src="@drawable/button_middle" />
    
    <nine-patch android:src="@drawable/button_right_side" />
    

    res/layout/main.xml:

    <button android:background="@drawable/button_background" />
    

    Is this possible?

  • seema
    seema about 9 years
    It would give better results if "dp" is used instead of "px". Using px will result in very small left and right most buttons in high density devices.