Search code examples
androidshapesselecteditemforeground

Set foreground to imageview


I set foreground to my imageview to select when it has been selected. This works fine in android 6 version. On select nothing changes in min versions. Please help me.

<ImageView
        android:id="@+id/style_list_item_image_view"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:layout_gravity="center"
        android:adjustViewBounds="true"
        android:foreground="@drawable/style_item_selector"
        android:scaleType="center"
        android:drawSelectorOnTop="true"
        android:clipChildren="true"
        android:clipToPadding="true"/>

style_item_selector.xml

<selector xmlns:android="http://schemas.android.com/apk/res/android">
    <item android:state_selected="true">
        <shape xmlns:android="http://schemas.android.com/apk/res/android">
            <size android:width="60dp" android:height="80dp" />
            <stroke android:width="1dp" android:color="#ff3591" />
            <solid android:color="@color/transparent100" />
            <corners android:radius="1dp" />
        </shape>
    </item>
</selector>

Solution

  • I have a solution for you

    Selector would be like this

    <selector xmlns:android="http://schemas.android.com/apk/res/android">
    <item android:state_pressed="true">
        <shape xmlns:android="http://schemas.android.com/apk/res/android" android:shape="rectangle">
            <size android:width="60dp" android:height="80dp" />
            <stroke android:width="1dp" android:color="#ff3591" />
            <solid android:color="@android:color/transparent" />
            <corners android:radius="1dp" />
        </shape>
    </item>
    

    ImageView need some wrap up

    <FrameLayout
        android:id="@+id/share"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:layout_centerHorizontal="true"
        android:layout_centerVertical="true"
        android:foreground="@drawable/style_item_selector">
    
    
        <ImageView
        android:id="@+id/style_list_item_image_view"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:layout_gravity="center"
        android:adjustViewBounds="true"
        android:scaleType="center"
        android:drawSelectorOnTop="true"
        android:clipChildren="true"
        android:clipToPadding="true"/>
    </FrameLayout>
    

    Hope this works for you!

    Make sure you attach onClickListener to the FrameLayout