Beppi's Beppi's - 19 days ago 9
Android Question

setTranslationY not initialized correctly

I created two short methods to help me to show or hide a view when a certain checkbox is checked.
I have a Init method, in which I initialize a checkbox and a view, and a toggle method that is called from inside the checkbox status change listener and toggle the view status with an animation.

void toggleViewVisibility(final boolean b, final View v) {
v.setAlpha(b ? 0.0f : 1.0f);
v.setTranslationY(b ? v.getHeight() : 0);
if (b) {
v.setVisibility(View.VISIBLE);
v.animate().alpha(1.0f).translationY(0).setDuration(400);
} else {
v.animate().alpha(0.0f).translationY(v.getHeight()).setDuration(400).setListener(new Animator.AnimatorListener() {
@Override public void onAnimationStart(Animator animator) {}
@Override public void onAnimationEnd(Animator animator) { v.setVisibility(View.GONE); }
@Override public void onAnimationCancel(Animator animator) {}
@Override public void onAnimationRepeat(Animator animator) {}
});
}
}

void toggleViewVisibilityInit(final boolean b, final View v, final AnimateCheckBox c) {
v.setAlpha(b ? 1.0f : 0.0f);
v.setTranslationY(b ? 0 : v.getHeight());
v.setVisibility(b ? View.VISIBLE : View.GONE);
c.setChecked(b);
}


It works fine with the alpha animation, but has a small problem with the translation animation, although they are treated and initialized in the exact same way. Why?

In particular, the translation works fine whenever the checkbox status changes, but when the checkbox starts off, so the view is invisible, only at the VERY FIRST status change the view appears with alpha animation but does not perform the translation animation.
It looks like that when the view has been just created, it's translation status is not initialized, while alpha status is, although it is done in the toggleViewVisibilityInit() method.

Does anybody know why this should happen? It looks like as soon as the view is created the translation is not taken into consideration.

Answer

The view is not yet drawn so it's height is unknown (thus equals 0).

If you know this, it is easy to look for solutions, eg. getWidth() and getHeight() of View returns 0

Hope this helps!

Comments