Я могу переместить ImageView, только если его размер равен match_parent - PullRequest
0 голосов
/ 01 октября 2018

Я сделал программу, которая перемещает 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 не двигаетсябольше.Есть ли у вас какие-либо идеи?Спасибо

1 Ответ

0 голосов
/ 01 октября 2018

Хорошо, проблема была в том, что в ConstraintLayout я устанавливал поля без установки ограничений.Я добавил

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

и теперь он работает

...