我制作了一个程序,可以在屏幕上移动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将不再移动。你有什么想法? 谢谢
答案 0 :(得分:0)
好吧,问题是在ConstraintLayout中我设置了边距而不设置约束。 我已添加
app:layout_constraintTop_toTopOf="parent
app:layout_constraintLeft_toLeftOf="parent"
现在可以了