Android Studio - 移动视图(线性布局)

Android Studio - Move View (Linear Layout)

移动布局已经将近 6 天了,但完全没有成功,尝试了很多来自互联网的帮助,但 none 有帮助..

我希望使用 OnTouchListener 将 llPic1 和 llPic2 移动到 ivNjeri 之上。 所以玩家可以决定哪一个需要移动到 ivNjeri 之上。

使用此代码,它会在移动时振动,并且 llPic1 和 llPic2 在 ivNjeri 下:

float dx = 0, dy = 0, x = 0, y = 0;

@Override
public boolean onTouch(View view, MotionEvent event) {
    switch (event.getAction()) {
        case MotionEvent.ACTION_DOWN: {
            x = event.getX();
            y = event.getY();
            dx = x - view.getX();
            dy = y - view.getY();
        }
        break;
        case MotionEvent.ACTION_MOVE: {
            view.setX(event.getX() - dx);
            view.setY(event.getY() - dy);
        }
        break;
        }
        return true;
    }

我也在尝试很多其他代码,但 none 有效,任何帮助都会非常非常有用:)

如果您只是想制作动画,请查看为什么不使用 Animation,如下所示:

TranslateAnimation animation = new TranslateAnimation(0.0f, 400.0f,0.0f, 0.0f);        
//  new TranslateAnimation(xFrom,xTo, yFrom,yTo)

animation.setDuration(5000);  // animation duration 
animation.setRepeatCount(1);  // animation repeat count
animation.setRepeatMode(1);   // repeat animation (left to right, right to left )
//animation.setFillAfter(true);      

llPic1.startAnimation(animation);  // start animation  

您可以尝试本教程 link。我想你需要删除你的 pic 1 或 pic2(如果你想在拖动后消失。)然后你应该在 ivNjeri view

上添加另一个图像视图

您应该只使用 1 个 ViewGroup,它包含所有图像,包括要重叠的图像和要移动的图像。

为什么图片不能超过大图?

右侧的小图在嵌套 LinearLayout 内,这限制了小图在 LinearLayout 内。这就是为什么您可以将图像移动到子 LinearLayout 内部但不能超出边界的原因。

一个使用 RelativeLayout 和大图固定宽度修复它的例子:

<RelativeLayout 
    xmlns:android="http://schemas.android.com/apk/res/android"
    android:id="@+id/activity_main"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    android:orientation="horizontal">

    <ImageView
        android:id="@+id/bigimage"
        android:layout_width="200dp"
        android:layout_height="300dp"
        android:src="@drawable/ic_launcher"/>

    <ImageView
        android:id="@+id/smallimage"
        android:layout_width="match_parent"
        android:layout_height="100dp"
        android:src="@drawable/ic_launcher"
        android:layout_toRightOf="@id/bigimage"/>

    <ImageView
        android:layout_width="match_parent"
        android:layout_height="100dp"
        android:src="@drawable/ic_launcher"
        android:layout_toRightOf="@id/bigimage"
        android:layout_below="@id/smallimage"/>

</RelativeLayout>

如果您想保持精确的体重,请查看 https://developer.android.com/reference/android/support/percent/PercentFrameLayout.html https://developer.android.com/reference/android/support/percent/PercentRelativeLayout.html

这可以让您控制体重,并且可以在 1 个视图中容纳所有视图 ViewGroup