如何拖动imageView(不是它的影子)?

时间:2014-12-23 23:00:00

标签: android image imageview touch drag

我知道如何使用dragEvent在屏幕上拖动imageView的阴影。但我想要做的是移动imageView,改变它的坐标。当我拖动图像时,它的左侧和顶部不会改变(我创建了一个定时打印值的时间戳,即使我拖动图像时坐标也不会改变)。这是因为我正在移动阴影,但我想使用拖动事件来移动imageView本身。

方法:

private final class MyTouchListener implements View.OnTouchListener {
public boolean onTouch(View view, MotionEvent motionEvent) {
    if (motionEvent.getAction() == MotionEvent.ACTION_DOWN) {
        ClipData data = ClipData.newPlainText("", "");
        View.DragShadowBuilder shadowBuilder = new View.DragShadowBuilder(view);
        view.startDrag(data, shadowBuilder, view, 0);
        view.setVisibility(View.INVISIBLE);
        return true;
    } else {
        return false;
    }
}

}

class MyDragListener implements View.OnDragListener {
Drawable enterShape = getResources().getDrawable(R.drawable.box);
Drawable normalShape = getResources().getDrawable(R.drawable.box);

@Override
public boolean onDrag(View v, DragEvent event) {
    int action = event.getAction();
    switch (event.getAction()) {
        case DragEvent.ACTION_DRAG_STARTED:
            System.out.println("Action is DragEvent.ACTION_DRAG_STARTED");
            Log.v(LOGS, "box " + box.getX());
            // do nothing
            break;
        case DragEvent.ACTION_DRAG_ENTERED:
            System.out.println("Action is DragEvent.ACTION_DRAG_ENTERED");
            Log.v(LOGS, "box " + box.getX());
            //v.setBackgroundDrawable(enterShape);
            v.setBackgroundResource(R.drawable.box);
            break;
        case DragEvent.ACTION_DRAG_EXITED:
            System.out.println("Action is DragEvent.ACTION_DRAG_FINISHED");
            Log.v(LOGS, "box " + box.getX());
            //v.setBackgroundDrawable(normalShape);
            v.setBackgroundResource(R.drawable.box);
            break;
        case DragEvent.ACTION_DROP:
            // Dropped, reassign View to ViewGroup
            View view = (View) event.getLocalState();
            ViewGroup owner = (ViewGroup) view.getParent();
            owner.removeView(view);
            LinearLayout container = (LinearLayout) v;
            container.addView(view);
            view.setVisibility(View.VISIBLE);
            break;
        case DragEvent.ACTION_DRAG_ENDED:
            //v.setBackgroundDrawable(normalShape);
        default:
            break;
    }
    return true;
}

}

0 个答案:

没有答案