View.OnDragListener()方法不会调用

时间:2018-11-22 19:12:02

标签: android android-layout

我有这个自定义AppCompatImageView类。当布局膨胀时,我看到调用了构造函数,并从日志中设置了侦听器

  

DragView2()

     

收听者设置

但是我没有看到指示与自定义视图进行交互时调用列表方法View.OnDragListener的日志。

为什么不调用View.OnDragListener

这是自定义的AppCompatImageView

public class DragView2 extends AppCompatImageView
implements View.OnDragListener{

    private static final String TAG = DragView2.class.getSimpleName();

    public DragView2(Context context) {
        super(context, null);
        Log.d(TAG,"DragView2()");
        this.setOnDragListener(this);
        Log.d(TAG,"listener set");

    }

    public DragView2(Context context, AttributeSet attrs) {
        super(context, attrs, 0);
        Log.d(TAG,"DragView2()");
        this.setOnDragListener(this);
        Log.d(TAG,"listener set");
    }

    @Override
    public boolean onDrag(View v, DragEvent event) {
        Log.d(TAG,"onDrag()");
        Log.d(TAG,"event.getAction() = "+event.getAction());
        return false;
    }
}

1 个答案:

答案 0 :(得分:0)

即使从onTouch,我也需要触发拖动,因此,我必须设置两个侦听器

this.setOnTouchListener(this);
this.setOnDragListener(this);

这是课程

public class DragView2 extends AppCompatImageView
implements View.OnDragListener, View.OnTouchListener{

    private static final String TAG = DragView2.class.getSimpleName();

    public DragView2(Context context) {
        super(context, null);
        Log.d(TAG,"DragView2()");
        this.setOnTouchListener(this);
        this.setOnDragListener(this);
        Log.d(TAG,"listener set");

    }

    public DragView2(Context context, AttributeSet attrs) {
        super(context, attrs, 0);
        Log.d(TAG,"DragView2()");
        this.setOnTouchListener(this);
        this.setOnDragListener(this);
        Log.d(TAG,"listener set");
    }

    @Override
    public boolean onTouch(View view, MotionEvent motionEvent) {
        Log.d(TAG,"onTouch()");
        Log.d(TAG," motionEvent.getAction() = "+motionEvent.getAction());

        if (motionEvent.getAction() == MotionEvent.ACTION_DOWN) {
            ClipData data = ClipData.newPlainText("", "");
            DragShadowBuilder shadowBuilder = new View.DragShadowBuilder(
                    view);
            view.startDrag(data, shadowBuilder, view, 0);
            view.setVisibility(View.INVISIBLE);
            return true;
        } else {
            return false;
        }
    }

    @Override
    public boolean onDrag(View v, DragEvent event) {
        Log.d(TAG,"onDrag()")
        return true;
    }
}