Search code examples
androidlayout

how to set background AND border at the same time, by selector


I want my layout has ALWAYS a border AND, if selected, a different background color. I thought it should work with:

<?xml version="1.0" encoding="utf-8"?>
<selector xmlns:android="http://schemas.android.com/apk/res/android">
    <item android:state_selected="true">
        <color android:color="@color/selected_color"/>
        <shape android:shape="rectangle">
            <stroke android:width="1dip" android:color="@android:color/black"/>
        </shape>
    </item>
    <item android:state_selected="false">
        <shape android:shape="rectangle">
            <stroke android:width="1dip" android:color="@android:color/black" />
        </shape>
    </item>
</selector>

But I only get border if NOT selected.

I can't find what gross mistake I'm making. I tried just about everything I could find as a solution to this type of problem, without ever obtaining the desired result.


Solution

  • Hey If I understand you right you want a Border in both cases so Just change your code and add solid color to your shape and it will solve your problem your code will be like this

        <?xml version="1.0" encoding="utf-8"?>
    <selector xmlns:android="http://schemas.android.com/apk/res/android">
        <item android:state_selected="true">
            <shape android:shape="rectangle">
                <solid android:color="@color/blue_result"/>
                <stroke android:width="10dp" android:color="@android:color/black"/>
            </shape>
        </item>
        <item android:state_selected="false">
            <shape android:shape="rectangle">
                <stroke android:width="1dp" android:color="@android:color/black" />
            </shape>
        </item>
    </selector>
    

    The Result when selected :

    enter image description here