Home » Android » android – Difference between setTranslationX/Y and offsetLeftAndRight/offsetTopAndBottom?

android – Difference between setTranslationX/Y and offsetLeftAndRight/offsetTopAndBottom?

Posted by: admin May 14, 2020 Leave a comment


I’m working with a CoordinatorLayout in which child views positions are being animated with the ViewCompat.offsetLeftAndRight and ViewCompact.offsetTopAndBottom APIs.

When a child view is added or removed from the CoordinatorLayout, the layout operation resets the position of each child to the top left corner of the screen, i.e. without any offset.

This article provides a solution, by setting a layout listener on the child view and restoring old positions.

I noticed that using the setTranslationX and setTranslationY APIs, this problem does not occur. Children keep their position after parent layout events.

How should I decide between these two sets of APIs for arranging my views on screen? I’m wary of using either without understanding their differences. I did not get a good understanding by reading the official documentation.

How to&Answers:

Quite old question after many months I have few explanations:

First things first. Offset will move the view horizontally or vertically similarly to translate but it’s used for permanent results.

When you use View#offsetTopAndBottom(int offset) then internally it has these functionality:

mTop += offset;
mBottom += offset;

On the other hand tranlate is an variable which is calculated in addition to this top/bottom/left/right positions and mostly handy in animations.

Both methods will trigger a layout refresh if needed.

More have been explained by Nick Butcher in this nice video: https://www.youtube.com/watch?v=86p1GPEv_fY&t=5m42s

Regarding CoordinatorLayout are you by any change setting margins to the children? E.g. BottomSheetBehavior does not work well with margins since it ignores them. I think this might be the case for you.