RecyclerView:如何在顶部模拟ListView的绘图选择器?

dev*_*ole 5 android android-appcompat android-support-library android-recyclerview

我想创建一个RecyclerView在其项目之上绘制选择器.它应该在项目的顶部呈现,这意味着我不能简单地设置StateListDrawable为项目背景.

我对压制状态特别感兴趣,即如果(并且仅当)按下某个项目,应该绘制一些东西.

RecyclerView.ItemDecoration能够绘制一个项目RecyclerView.这是我到目前为止所尝试的:

public final class ItemPressedDecoration extends RecyclerView.ItemDecoration {
    private final Rect rect = new Rect();

    @Override
    public void onDrawOver(Canvas c, RecyclerView parent, RecyclerView.State state) {
        final int count = parent.getChildCount();
        for (int index = 0; index < count; index++) {
            final View child = parent.getChildAt(index);
            if (child.isPressed()) {
                drawOverlay(c, child);
            }
        }
    }

    private void drawOverlay(Canvas c, View child) {
        c.save();
        rect.set(child.getLeft(), child.getTop(), child.getRight(), child.getBottom());
        c.clipRect(rect);
        c.drawColor(0x80ff0000);
        c.restore();
    }
}
Run Code Online (Sandbox Code Playgroud)

问题是,RecyclerView如果其中一个子项的可绘制状态发生更改,则似乎不会重新绘制项目装饰.那我怎么做呢?

我试图从它的方法添加RecyclerView.OnItemTouchListener和调用recyclerView.invalidate(),onInterceptTouchEvent()但这不起作用.

Yuk*_*ida 7

如果您可以FrameLayout以root身份使用,并且您的选择器是半透明的,则下面的布局可能很有用.

android:foreground不是 android:background

布局/ view_listitem.xml

<FrameLayout
  android:layout_width="match_parent"
  android:layout_height="wrap_content"
  android:foreground="@drawable/your_selector">

  <!-- your list items -->

</FrameLayout>
Run Code Online (Sandbox Code Playgroud)


dev*_*ole 2

我找到了一个似乎有效的解决方案。我必须子类化RecyclerView才能使视图无效并强制再次绘制项目装饰。

public class ChildDrawableStateRecyclerView extends RecyclerView {
    /* constructors omitted */

    @Override
    public void childDrawableStateChanged(View child) {
        super.childDrawableStateChanged(child);

        // force ItemDecorations to be drawn
        invalidate();
    }
}
Run Code Online (Sandbox Code Playgroud)

我不知道这是否是正确的方法。如果您有更好的答案,请提供。

我还必须检查是否可以通过这种方式实现连锁反应。