Question

I've coded a Drag and drop behaviour for my Android application. So far it works perfectly on my HTC One and on my Samsung S3. Basically, it just sets the leftMargin and the topMargin on the view to move.

When I try it on a Xperia Arc S, I can set the topMargin and move the view vertically without any problem. But once I try to move it horizontaly (Setting the leftMargin), it doesn't work. I can't even set the leftMargin programatically.

I got a very simple code, but I can't find out what is going wrong on the Xperia and why it does work on the other devices I got.

params.topMargin = (int) event.getRawY() - view.getHeight();
params.leftMargin = (int) event.getRawX() - (view.getWidth() / 2);

// Set bounds
if (params.topMargin < 0) params.topMargin = 0;
if (params.topMargin + viewHeight * 3/2 > display.heightPixels) params.topMargin = display.heightPixels - viewHeight * 3/2;
if (params.leftMargin < 0) params.leftMargin = 0;
if (params.leftMargin + viewWidth > display.widthPixels) params.leftMargin = display.widthPixels - viewWidth;

view.setLayoutParams(params);

If I display the values of leftMargin, display.widthPixels and viewWidth, I got something which look good. (Eg. leftMargin = anything between -100 to 600 or so. widthPixels = 480 and viewWidth = 316 at the moment).

Is there something wrong with the Xperia or is there any error in my code ?

Thanks for your precious help.

EDIT: Solution was (Regarding Ved Prakash post)

FrameLayout.LayoutParams paramsOld = (FrameLayout.LayoutParams) view.getLayoutParams();
FrameLayout.LayoutParams params = new FrameLayout.LayoutParams(paramsOld.width, paramsOld.height, Gravity.TOP);

params.topMargin = (int) event.getRawY() - view.getHeight();
params.leftMargin = (int) event.getRawX() - (view.getWidth() / 2);

// Set bounds
if (params.topMargin < 0) params.topMargin = 0;
if (params.topMargin + viewHeight * 3/2 > display.heightPixels) params.topMargin = display.heightPixels - viewHeight * 3/2;
if (params.leftMargin < 0) params.leftMargin = 0;
if (params.leftMargin + viewWidth > display.widthPixels) params.leftMargin = display.widthPixels - viewWidth;

view.setLayoutParams(params);

view.invalidate();
Was it helpful?

Solution

Sony Xperia Arc S - Android 2.3

HTC One - Android 4.1

There is a problem in setting the layout with older versions of android.

Check the post: android-setting-left-right-margin-doesnt-work.

OTHER TIPS

Android 4.4 has some problem with layout Margin. So better try:

view.setPadding(left, top, right, bottom);
Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top