如何动态地将按下的颜色更改为选择器的其他颜色?

use*_*993 4 java android selector

这是我的列表选择器:(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>
Run Code Online (Sandbox Code Playgroud)

这是我的行列表(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>
Run Code Online (Sandbox Code Playgroud)

我想动态地将android:state_pressed ="true"android:drawable ="@ color/orange"改为其他颜色.我的目标是使每一行的按压颜色不同.有可能吗?

小智 9

影响每个项目的新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);
Run Code Online (Sandbox Code Playgroud)