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

2022-04-14 00:00:00 selector android java

这是我的列表选择器:(Item_seltor.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>

这是我的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>

我想要动态地将android:STATE_PRESSESS="true"android:Drawable="@COLOR/ONGLE"更改为其他颜色。我的目标是让每一行的压榨颜色不同。可以这样做吗?


解决方案

影响每个项目一个新的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);

相关文章