【问题标题】:Why won't the ImageView move?为什么 ImageView 不会移动?
【发布时间】:2019-08-25 21:38:02
【问题描述】:

我在做一个手机游戏,我想让ImageView在我按左右键的时候水平移动。

我已经尝试过 setX() 和 And Object Animator,但它仍然不会移动

左右按钮。

        btnRight.setOnClickListener(new View.OnClickListener() {
            public void onClick(View right) {
                x++;
                ObjectAnimator d = ObjectAnimator.ofFloat(first, "translationX", x);
                d.setDuration(2000);
                d.start();

            }
        });
        btnLeft.setOnClickListener(new View.OnClickListener() {
            public void onClick(View left) {
                x--;
                ObjectAnimator animation = ObjectAnimator.ofFloat(first, "translationX", x);
                animation.setDuration(2000);
                animation.start();

            }
        });

图像视图 XML

    <ImageView
        android:id="@+id/first"
        android:layout_width="100dp"
        android:layout_height="100dp"
        android:layout_marginStart="8dp"
        android:layout_marginLeft="8dp"
        android:layout_marginTop="160dp"
        android:layout_marginEnd="166dp"
        android:layout_marginRight="168dp"
        android:layout_marginBottom="471dp"
        android:adjustViewBounds="true"
        android:background="#00FFFFFF"
        android:contentDescription="@android:string/untitled"
        android:scaleType="fitXY"
        app:layout_constraintBottom_toBottomOf="parent"
        app:layout_constraintEnd_toEndOf="parent"
        app:layout_constraintHorizontal_bias="0.963"
        app:layout_constraintStart_toStartOf="parent"
        app:layout_constraintTop_toTopOf="parent"
        app:layout_constraintVertical_bias="1.0"
        app:srcCompat="@android:color/background_light"
        tools:srcCompat="@android:color/background_light" />

当我使用 setX 时,如果我同时按下两个按钮,对象总是会向左移动,并且会停留在那里。当我使用 ObjectAnimator 时,它只是停留在那里。

【问题讨论】:

  • 您将其移动一个像素,您将无法看到增量,通过增加增量值使其更加夸张。

标签: android


【解决方案1】:

ObjectAnimator 应该没问题。
我试过你的代码,它可以工作,但是平移距离真的很小,我必须多次点击按钮才能看到明显的动作。
您可以将x++ 更改为x += 10 甚至x += 50 以检查它是否真的有效。

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2019-01-19
    • 1970-01-01
    • 1970-01-01
    • 2012-05-02
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多