Skip to content
Advertisement

How to change pressed color to other color of selector dynamically?

that’s my selector for list:(item_selector.xml)

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

that’s my row of list(row_item.xml)

<RelativeLayout 
    xmlns:android="http://schemas.android.com/apk/res/android"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    android:orientation="vertical"
    android:background="@color/alarm_item_drawer_selector"
    >

    <ImageView 
        android:id="@+id/item_icon"
        android:layout_width="30dp"
        android:layout_height="30dp"
        android:layout_centerHorizontal="true"
        android:paddingTop="5dp"
        android:paddingBottom="2dp"
        android:src="@drawable/ic_launcher"/>

    <TextView      
        android:id="@+id/item_title"
        style="@style/DrawerItemTextStyle"
        android:textColor="@color/text_drawer_item_selector"
        android:layout_centerHorizontal="true"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:layout_below="@id/item_icon" />

</RelativeLayout>

I want to change android:state_pressed=”true” android:drawable=”@color/orange” to other color dynamically. My goal, to make pressed color for each row different. Is it possible to do?

Advertisement

Answer

Affect to each item a new StateListDrawable.

    StateListDrawable stateListDrawable= new StateListDrawable();
    stateListDrawable.addState(new int[] {android.R.attr.state_pressed}, new ColorDrawable(getContext().getResources().getColor(R.color.anycolor)));
    stateListDrawable.addState(new int[] {android.R.attr.state_focused}, new ColorDrawable(getContext().getResources().getColor(R.color.anycolor)));
    stateListDrawable.addState(new int[] {android.R.attr.state_selected}, new ColorDrawable(getContext().getResources().getColor(R.color.anycolor)));
    stateListDrawable.addState(new int[] {}, new ColorDrawable(getContext().getResources().getColor(R.color.anycolor)));

    view.setBackgroundDrawable(stateListDrawable);
User contributions licensed under: CC BY-SA
7 People found this is helpful
Advertisement