使用Item Touch Helper android拖动阴影

时间:2016-02-19 13:05:39

标签: android android-recyclerview

Android中的ItemTouchhelper类只能在recyclerview周围移动整个视图。是否可以使用Item touchHelper类来拖动视图的阴影(原始视图在其位置固定)?

3 个答案:

答案 0 :(得分:2)

我覆盖onChildDraw并制作了自己的影子

public void onChildDraw(Canvas c, RecyclerView recyclerView, RecyclerView.ViewHolder viewHolder, float dX, float dY, int actionState, boolean isCurrentlyActive) {
        super.onChildDraw(c, recyclerView, viewHolder, dX, dY, actionState, isCurrentlyActive);

        if (isCurrentlyActive) {
            if (actionState == ItemTouchHelper.ACTION_STATE_DRAG) {
                // make shadown

                    isRotated = true;
                }
            }
        } else {
            // view is going back to orig
            if (isRotated) {

                // undo shadow
            }
        }
    }

答案 1 :(得分:2)

这是在拖动的项目上实现阴影的简单方法(对于API> = 21,因为它依赖于海拔)。

attrs.xml中声明属性:

<attr name="draggedItemElevation" format="dimension"/>

在主题中设置属性值:

<style name="AppTheme" parent="...">
    <item name="draggedItemElevation">2dp</item>
</style>

将此回调用于ItemTouchHelper

class DragItemTouchHelperCallback : ItemTouchHelper.Callback() {

    // Get elevation in pixels from ?attr/draggedItemElevation.
    private val elevation = context.obtainStyledAttributes(
            intArrayOf(R.attr.editDraggedItemElevation)).use {
        it.getDimensionPixelSize(0, 0).toFloat()
    }

    override fun onChildDraw(c: Canvas, recyclerView: RecyclerView, viewHolder: RecyclerView.ViewHolder,
                             dX: Float, dY: Float, actionState: Int, isCurrentlyActive: Boolean) {
        val view = viewHolder.itemView
        view.translationX = dX
        view.translationY = dY
        if (isCurrentlyActive) {
            ViewCompat.setElevation(view, elevation)
        }
    }

    override fun clearView(recyclerView: RecyclerView, viewHolder: RecyclerView.ViewHolder) {
        val view = viewHolder.itemView
        view.translationX = 0f
        view.translationY = 0f
        ViewCompat.setElevation(view, 0f)
    }

    override fun getMovementFlags(recyclerView: RecyclerView,
                                  viewHolder: RecyclerView.ViewHolder): Int {
        // ...
    }

    override fun onMove(recyclerView: RecyclerView,
                        viewHolder: RecyclerView.ViewHolder,
                        target: RecyclerView.ViewHolder): Boolean {
        // ...
    }

    override fun onSwiped(viewHolder: RecyclerView.ViewHolder, direction: Int) {
        // ...
    }
}

这将暂时将拖动的项目高程更改为?attr/draggedItemElevation,然后在放置项目时将其重新设置为0。

答案 2 :(得分:0)

所以,你只想要一个带有阴影的“预览”拖动......?

当您致电DragShadow时,很容易实现startDrag

view.startDrag(clipData, new View.DragShadowBuilder(v), null, 0); //clipData can be null.

关于如何处理Drag&amp; amp;的优秀教程请注意,我推荐Paul Burke中的那个。他定义了一个背景,向用户显示视图的放置位置。

如果这不能解答您的问题,请在您的问题中提供更多详细信息。