How can I programmatically translate an arbitrary view without using an animation (android.view.animation.*
)?
API 11 introduced setTranslationX
You also can try this code: https://github.com/BeyondAR/beyondar/blob/development/android/BeyondAR_Framework/src/com/beyondar/android/view/CustomLayout.java
Use the method setPosition.
One alternative to TranslateAnimation is to subclass a View and translate the Canvas on dispatchDraw. Something like:
public class TranslateView extends View {
private float mTranslationX = 0;
private float mTranslationY = 0;
private boolean mWillUseSDKTranslation = true;
@Override
protected void dispatchDraw(final Canvas canvas) {
if (mWillUseSDKTranslation == false) {
// keep track of the current state
canvas.save(Canvas.MATRIX_SAVE_FLAG);
// translate
canvas.translate(mTranslationX, mTranslationY);
// draw it
super.dispatchDraw(canvas);
// restore to the previous state
canvas.restore();
} else {
super.dispatchDraw(canvas);
}
}
public void setTranslationValue(final float aTranslationX, final float aTranslationY) {
if (android.os.Build.VERSION.SDK_INT < Build.VERSION_CODES.HONEYCOMB) {
mWillUseSDKTranslation = false;
mTranslationX = aTranslationX;
mTranslationY = aTranslationY;
invalidate();
} else {
setTranslationX(aTranslationX);
setTranslationY(aTranslationY);
}
}
}
Favorited because I would love to be proven wrong on this one, but I ran into a similar wall when doing some Drag-n-Drop investigations awhile back.
I'm pretty sure you're stuck with offsetTopAndBottom()
and offsetLeftAndRight()
for moving a View
around without an animation in early APIs. The big downside here is that these methods actually modify the top/bottom/left/right values, so you have to do some pretty heavy tracking if you want to go back to where you started from.
Another option would be to simply use a TranslateAnimation
with a VERY short duration and set to fillAfter
...
Other options require subclassing, and still aren't pretty, like translating the Canvas
the View
draws on. The problem here is you also have to create a parent that doesn't clip it's children so the view can draw outside its own bounds.
I was having the same problem. I was able to achieve the translation by manipulating the layoutparams, specifically the margins, of the views I wanted to translate. You can use negative values for the margins btw.
Yes, you can use TranslateAnimation. With fillAfter set to true your view will stay translated even after the animation ends. Here is an example:
TranslateAnimation anim=new TranslateAnimation(0, 0, 20, 20);
anim.setFillAfter(true);
anim.setDuration(0);
yourView.startAnimation(anim);
A workaround I found was to set negative margins using:
layoutParams.setMargins(left, top, right, bottom);
yourView.setLayoutParams(layoutParams);