2

I am creating an Android application that programmatically creates an ImageView, to be dragged and placed anywhere on screen. I can drag the view along the screen, but when it is dragged to the bottom and right sides of the screen, the view shrinks instead of just leaving the screen. I want to avoid this behavior.

I came across this question from a few years ago: Android: Drag View Outside Screen It appears to be the same question as my own, but was left unanswered. I have tried a few other suggested methods, including setting 'clipChildren' and 'clipToPadding' to false: Android: Display Image Slightly Outside A Relative Layout

Again, this behavior only occurs when dragging the image to the bottom and right sides of the screen. When dragged to the top or left sides, the image goes off the screen.

Community
  • 1
  • 1
Bryan
  • 14,756
  • 10
  • 70
  • 125

1 Answers1

1

The view shrinks because at some point you change the view's width/height, i.e. say getRight() - getLeft() is forced to decrease because there is not enough space on the screen.

Anyway, setting view's coordinates directly is not something you should do. Instead implement your custom ViewGroup/layout:

  • Override onLayout()
  • Iterate through children: use your custom logic to determine top and left coordinate for each child. In your case it would be using touch events to calculate the coordinates during dragging. For the right and bottom coordinates you can add the measured width/height of the child.
  • On each child call child.layout(left, top, right, bottom)

For an example see the code of FrameLayout at line 513 and the docs for onLayout().

Gil Vegliach
  • 3,542
  • 2
  • 25
  • 37
  • 1
    I'm sure your method would work, though I haven't tested it. I found it much easier to use setTranslationX() and setTranslationY() instead (though I had to increase my minimum API first). – Bryan Jul 21 '15 at 17:48