仅当 ImageView 的大小为 match_parent 时,我才能移动它

I can move an ImageView only if its size is match_parent

我制作了一个在屏幕上移动 ImageView 的程序。这是代码:

layout.xml

<it.lorfioroni.scanner.customImageView
    android:id="@+id/customImageView"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    android:src="@drawable/ic_launcher_background"
    android:background="@color/colorAccent"
    android:scaleType="matrix"
    />

</android.support.constraint.ConstraintLayout>

customImageView.java

public class customImageView extends android.support.v7.widget.AppCompatImageView {
public customImageView(Context context) {
    super(context);
}

public customImageView(Context context, @Nullable AttributeSet attrs) {
    super(context, attrs);
}

public customImageView(Context context, @Nullable AttributeSet attrs, int defStyleAttr) {
    super(context, attrs, defStyleAttr);
}

private int xDelta, yDelta;

@Override
public boolean onTouchEvent(MotionEvent event) {
    final int x = (int) event.getRawX();
    final int y = (int) event.getRawY();

    switch (event.getAction() & MotionEvent.ACTION_MASK) {

        case MotionEvent.ACTION_DOWN:
            ConstraintLayout.LayoutParams lParams = (ConstraintLayout.LayoutParams)
                    this.getLayoutParams();

            xDelta = x - lParams.leftMargin;
            yDelta = y - lParams.topMargin;
            break;

        case MotionEvent.ACTION_UP:
           Log.i("ciao", "thanks for new location");
            break;

        case MotionEvent.ACTION_MOVE:
            ConstraintLayout.LayoutParams layoutParams = (ConstraintLayout.LayoutParams) this
                    .getLayoutParams();
            layoutParams.leftMargin = x - xDelta;
            layoutParams.topMargin = y - yDelta;
            layoutParams.rightMargin = 0;
            layoutParams.bottomMargin = 0;
            this.setLayoutParams(layoutParams);
            break;
    }
    if(this.getParent() instanceof View)
        ((View)this.getParent()).invalidate();
    return true;
}
}

而且效果很好,我可以在屏幕上自由移动图像。问题是虽然图像在左角很小(没关系),但 imageView 是全屏的...我尝试设置

android:layout_width="wrap_content"
android:layout_height="wrap_content"

但是当我这样做时,imageView 将不再移动。你有什么想法? 谢谢

好的,问题是在 ConstraintLayout 中我设置了边距而没有设置约束。 我添加了

app:layout_constraintTop_toTopOf="parent
app:layout_constraintLeft_toLeftOf="parent"

现在可以使用了