Search code examples
androidanimationandroid-activityoncreatemeasurement

Animation of View in onCreate() method


I want to animate TextView when activity has been launched, in onCreate() method. However, when I try to get view's height or width it's always 0. In my case it's important to know view's height or width because I want to set the translation for Y or X. For example, consider this code:

   TextView text=(TextView)(findViewById(R.id.text));
    text.setText(R.string.some_text);
    text.setTranslationY(-text.getHeight());

    ObjectAnimator moveTextAnimator=ObjectAnimator.ofFloat(text,"translationY",-text.getHeight(),0);
    moveTextAnimator.setDuration(1000);
    ObjectAnimator fadeTextAnimator=ObjectAnimator.ofFloat(text,"alpha",0,1);
    fadeTextAnimator.setDuration(2000);


    AnimatorSet textAnimatorSet=new AnimatorSet();
    textAnimatorSet.playSequentially(moveTextAnimator,fadeTextAnimator);
    textAnimatorSet.start();

I want to run this code in onCreate() method. Do you know how to solve this problem? I believe that one of the solution is just simply to wait until the view will be drawn. However, what if I would like to run the same animations for every single view in my layout? Do I need to wait for every view? And how can I do it?


Solution

  • simply use text.post(new Runnable(){});

    call text.getHeight() in the runnable will get correct result;