szymonm
szymonm

Reputation: 1051

Android Drag&Drop with XML Layout

The idea was to create an interface with two "buttons" that are draggable.

I didn't want to use Canvas (problems with the bitmap in the memory and redrawing everything, etc.), so I decided to use the XML Layout with ImageView as buttons.

One button is central_vertical | left, the second one central (for example). The first one works fine, as it should, but the second one has strange margins on the both sides (left and right) and button cannot be dragged. I checked also other positions:

  1. top left corner - correct
  2. bottom left corner - move only possible in x-axis...
  3. top/bottom/center right - move only possible in y-axis

Of course the situation is the same for any button with those properties, not only for "the second one". The code is for every button the same. It's really strange, but I guess it is a problem of the XML Layout:

<?xml version="1.0" encoding="utf-8"?>
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="fill_parent"
android:layout_height="fill_parent">
    <LinearLayout
        android:layout_width="fill_parent"
        android:layout_height="fill_parent"
        android:layout_gravity="left"
        android:gravity="center_vertical|left" >
        <ImageView
            android:id="@+id/leftChar"
            android:src="@drawable/ukreska"
            android:layout_height="wrap_content"
            android:layout_width="wrap_content" />
    </LinearLayout>
    <LinearLayout
        android:layout_width="fill_parent"
        android:layout_height="fill_parent"
        android:gravity="center">

        <ImageView
            android:id="@+id/rightChar"
            android:layout_width="wrap_content"
            android:layout_height="wrap_content"
            android:src="@drawable/uotwarte" />
    </LinearLayout>
</RelativeLayout>

The position of the buttons are set with the Layout margin:

LinearLayout.LayoutParams lp = new LinearLayout.LayoutParams(new ViewGroup.MarginLayoutParams(
            LinearLayout.LayoutParams.WRAP_CONTENT,
            LinearLayout.LayoutParams.WRAP_CONTENT));
lp.setMargins(X, Y, 0, 0);
img.setLayoutParams(lp);

The position is calculated with event.getX() and event.getY()

The version of the Android SDK 2.2. I've checked on the emulator and on the phone - the same results.

Do you have any idea? Thanks in advance : )

Upvotes: 0

Views: 300

Answers (1)

szymonm
szymonm

Reputation: 1051

Found the mistake. In case someone has the same problem:

When using XML layout and drag&drop, make sure you set proper XML gravity property. I removed it completely and I decided to set margins on the beginning of the Activity.

Cheers!

Upvotes: 1

Related Questions