Search code examples
androidxmlcode-reuselayer-list

Android: Can I re-use a layer-list?


When implementing selectors for Buttons and ListView items, I keep finding that I want to reuse the same item/background for state_pressed and state_focused.

Instead of duplicating XML 'code', is it possible to re-use a ?

e.g. Here is my state_pressed 'code' - how can I get state_focused to use the same lump of 'code' without duplicating it all?

<?xml version="1.0" encoding="utf-8"?>
<selector
    xmlns:android="http://schemas.android.com/apk/res/android">

  <item android:state_pressed="true">
    <layer-list xmlns:android="http://schemas.android.com/apk/res/android">

    <!--  PDS: Side lowlight lines Inset so hidden underneath solid colour -->
    <item android:bottom="0dp" android:right="0dp" android:top="0dp" android:left="0dp">
      <shape>
          <solid  android:color="#00000000" />
          <stroke android:color="@color/butGreySelectFrame" android:width="4dp"/>
          <corners android:radius="4dp" />              
      </shape>     
    </item> 

    <!-- PDS: Solid colour --> 
    <item android:left="4dp" android:right="4dp" android:top="4dp" android:bottom="4dp">              
      <shape>
        <solid android:color="@color/butGreySelectBack" />
        <padding
            android:left="10dp"
            android:top="10dp"
            android:right="10dp"
            android:bottom="10dp" />
      </shape>
      </item>

    </layer-list>
</item>

Solution

  • Yes, any drawable can be reused in a selector.

    Just create a separate file for the layer-list, then reference it with

    <item android:state_xxx android:drawable="@drawable/the_resource" />