Simultaneous Translations on Android

后端 未结 1 447
轮回少年
轮回少年 2021-01-12 14:08

I\'m trying to do several translations simultaneously on Android.

I have 2 or more buttons on a layout (all the same size), and when I press one I want the others to

1条回答
  •  -上瘾入骨i
    2021-01-12 14:29

    Issue:

    It seems that setAnimation will acutally start the animation and probably asynchronously. However there might be a lock on setting the animation for the second view. There must be a dispatcher because setting the animation for the buttons in different order does not affect the fact that bottom one is faster.

    The solution is to prevent this hypothetical lock by creating two individual animations.

    Code:

    public void onClick(View view) {
        Button toMove = (Button) findViewById(R.id.button_test2);
        Button toMove2 = (Button) findViewById(R.id.button_test3);
    
        TranslateAnimation anim = new TranslateAnimation(0, -toMove
                .getWidth(), 0, 0);
        anim.setFillAfter(true);
        anim.setDuration(1000);
    
        TranslateAnimation anim2 = new TranslateAnimation(0, -toMove
                .getWidth(), 0, 0);
        anim2.setFillAfter(true);
        anim2.setDuration(1000);
    
        //THERE IS ONE MORE TRICK
    
        toMove.setAnimation(anim);
        toMove2.setAnimation(anim2);
    }
    

    Note:

    In the //THERE IS ONE MORE TRICK, you could add the following code to ensure that they move together. There still must be a lag of 1 millisecond or so.

    long time =AnimationUtils.currentAnimationTimeMillis();
    
    //This invalidate is needed in new Android versions at least in order for the view to be refreshed.
    toMove.invalidate(); 
    toMove2.invalidate();
    anim.setStartTime(time);
    anim2.setStartTime(time);
    

    0 讨论(0)
提交回复
热议问题