Search code examples
androidandroid-fragmentsfragmentfragmenttransactionobjectanimator

Start ObjectAnimator after fragment transaction


i have this method to scroll my textview from left to right:

public void scrollText() {
    float startX = 0 - scrollTxt.getWidth();
    float endX = scrollTxt.getWidth();
    ObjectAnimator anim = ObjectAnimator.ofFloat(scrollTxt, View.X, startX, endX);
    anim.setRepeatCount(ValueAnimator.INFINITE);
    anim.setRepeatMode(ValueAnimator.RESTART);
    anim.setDuration(9000);
    anim.start();
}

this method and the textview are in a fragment. i add this fragment in my activity with this code:

@Override
protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.activity_main);

    drawer = (DrawerLayout) findViewById(R.id.activity_main_drawer);

    MainFragment mainFragment = new MainFragment();
    FragmentManager fm = getSupportFragmentManager();
    FragmentTransaction ft = fm.beginTransaction();
    ft.add(R.id.activity_main_frame, mainFragment);
    ft.commit();

    NavigationView navigationView = (NavigationView) findViewById(R.id.activity_main_nav);
    navigationView.setNavigationItemSelectedListener(new MainNavigationListener(drawer));
}

i want to start animation when fragmnet added. i put scrollText() method in fragmnet's onResume but it didn't work.


Solution

  • This happens because scrollTxt.getWidth()is zero in onResume() because your fragment view hierarchy hasn't been measured yet. As a solution, you can postpone the animation start to the next layout pass by calling scrollTxt.post().

    Try this:

    @Override
    public void onResume() {
        super.onResume();
        scrollTxt.post(new Runnable() {
            @Override public void run() {
                scrollText();
            }
        });
    }