Search code examples
androidandroid-studioandroid-linearlayoutmoveontouchlistener

Android Studio - Move View (Linear Layout)


it is almost 6 days traying to move the layout, but no success at all, trying alot of helps from internet but none helps..

enter image description here

I want llPic1 and llPic2 to be moved above ivNjeri with OnTouchListener. So player to dicide which one need to be moved above ivNjeri.

With this code it vibrates on move and llPic1 and llPic2 goes under 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;
    }

enter image description here

I'm also trying alot of other codes but none works, any help will be very very appriciated :)


Solution

  • You should use only 1 ViewGroup which holds all the images including an image to be overlapped and images to move.

    Why image cannot go over the big image?

    The small image on right side is inside of nested LinearLayout which is restricting the small image to be within the LinearLayout. That is why you can move the image inside of the child LinearLayout but not go beyond the boundary.

    One example to fix it using RelativeLayout and fixed width on big image:

    <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>
    

    If you want to keep the precise weight, check out https://developer.android.com/reference/android/support/percent/PercentFrameLayout.html https://developer.android.com/reference/android/support/percent/PercentRelativeLayout.html

    This can give you weight control and can hold all views in 1 ViewGroup.