Search code examples
androidandroid-layoutandroid-xmlandroid-shape

Android - What is the difference between these three xml files?


What is the difference between these three xml files in android?

xml file with selector as root element

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

xml file with shape as root element

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

xml file with layer-list as root element

<?xml version="1.0" encoding="utf-8"?>
<layer-list xmlns:android="http://schemas.android.com/apk/res/android">
    <item>
        <shape android:shape="rectangle">
            <Further Designing ... />
            ...
        </shape>
    </item>
    <item android:bottom="1dp">
        <shape android:shape="rectangle">
            <Further Designing ... />
            ...
        </shape>
    </item>
</layer-list>

Which one is used in which case. A little examples will be more appreciated. Thanks!!!


Solution

  • Layer List
    From docs:
    A Drawable that manages an array of other Drawables. These are drawn in array order, so the element with the largest index is be drawn on top. Creates a LayerDrawable.

    This is used when you want to combine multiple drawables into one, for example you could use it to add a background to an icon.

    Selector (StateList)
    From docs:
    A StateListDrawable is a drawable object defined in XML that uses a several different images to represent the same graphic, depending on the state of the object. For example, a Button widget can exist in one of several different states (pressed, focused, or neither) and, using a state list drawable, you can provide a different background image for each state.

    It can used to show different drawables in different conditions.

    Shape
    From docs:
    An XML file that defines a geometric shape, including colors and gradients. Creates a GradientDrawable.

    This should be used when you want to show a single shape. It can be used inside a LayerList to add a shape to an image or it can be used with a selector to switch between shapes as well.

    Fun Part(hopefully)
    All 3 of these represent drawables so you can combine these to meet your needs. For example I could have selector as root element, which contains LayerList and each layer list can have shapes. When working with these dynamically, all 3 are subclasses of Drawable class.

    Check out documentation for more information: https://developer.android.com/guide/topics/resources/drawable-resource