在选择时设置视图背景颜色无法正常工作

时间:2019-03-24 08:59:26

标签: java android adapter

我正尝试增加在长按时更改回收视图项目颜色的功能。从下面的代码中,您可以看到长按后我如何将视图的选定状态设置为新状态。我发现非常奇怪的行为。

一系列长按期间会发生以下情况:

第一次长按-背景不会改变

第二次长按-选中背景更改

第三次长按-背景保持在选定状态

第四次长按-背景变为未选中

重复一次。

我已经挠了一段时间。有人知道为什么会这样吗?

长按功能

@Override
public void onItemLongClick(View view, int position) {
    view.setSelected(!view.isSelected());
    adapter.notifyItemChanged(position);
}

recycleview_log.xml

<LinearLayout
    xmlns:android="http://schemas.android.com/apk/res/android"
    android:layout_width="match_parent"
    android:layout_height="wrap_content"
    android:orientation="horizontal"
    android:background="@drawable/selected_item"
    android:padding="10dp">

selected_item.xml

<selector xmlns:android="http://schemas.android.com/apk/res/android">
    <item
        android:state_selected="true"
        android:drawable="@color/mainThemeDark"/>
    <item
        android:state_selected="false"
        android:drawable="@color/mainTheme" />
</selector>

0 个答案:

没有答案
相关问题