How to set Spinner drop-down selected item color AND touch highlight color

Viewed 46

I have a Spinner and in its drop-down I want to do the following 2 things - but I can't get them both to work together:

  1. In the drop-down, highlight the selected item blue.
  2. When the user touches a different item in the drop-down I want to have a momentary red highlight color (ripple?). But, it always shows a grey color that I can't change.

I can set the drop-down selected item color using this code:

private View getCustomDropDownView(final int position, View itemView, ViewGroup parent) {
    ...
    // all my viewholder code
    ...
    if (position == selectedIndex) {
        // Selected item
            itemView.setSelected(true);
            itemView.setPressed(true);
            itemView.setBackgroundColor(MaterialColors.getColor(getContext(), R.color.highlight_blue, Color.BLUE));
      } else {
        // Not selected
            itemView.setSelected(false);
            itemView.setPressed(false);
            itemView.setBackgroundColor(Color.TRANSPARENT);
      }
    ...
}

<androidx.appcompat.widget.AppCompatSpinner
    android:layout_width="match_parent"
    android:layout_height="wrap_content" />

But I can't seem to set a different touch-highlight color than the default grey. I try and do this with this code:

view_spinner_dropdown_item.xml

<RelativeLayout
    xmlns:android="http://schemas.android.com/apk/res/android"
    android:layout_width="match_parent"
    android:layout_height="wrap_content"
    android:background="@drawable/spinner_dropdown_item_touch_highlight">
    ...
</RelativeLayout>

spinner_dropdown_item_touch_highlight.xml

<selector xmlns:android="http://schemas.android.com/apk/res/android">
    <item android:state_selected="true" android:drawable="@color/red" />
    <item android:state_pressed="true" android:drawable="@color/red" />
    <item android:drawable="@android:color/transparent" />
</selector>

But when I touch a drop-down item it is momentarily highlighted in grey not red but I don't know why?

enter image description here

Just to note, if I comment out the selected item color lines in my adapter...

if (position == selectedIndex) {
     //Selected item
     itemView.setSelected(true);
     itemView.setPressed(true);
     //itemView.setBackgroundColor(MaterialColors.getColor(getContext(), R.color.highlight_blue, Color.GRAY));
else {
     // Not selected
     itemView.setSelected(false);
     itemView.setPressed(false);
     //itemView.setBackgroundColor(Color.TRANSPARENT);
}

...then I do get the red touch highlighted but no longer the selected item being blue.

enter image description here

0 Answers
Related