user1702512
user1702512

Reputation: 95

Animate RelativeLayout margin change

Code:

RelativLayout.LayoutParams params = (RelativLayout.LayoutParams) view1.getLayoutParams();
params.setMargins(50, 0, 0, 0);
view1.setLayoutParams(params);

The above code is working fine, but I want to animate it.

Upvotes: 4

Views: 6359

Answers (2)

Alexandre G
Alexandre G

Reputation: 1693

Or better yet, use Animation:

Animation animation = new Animation() {
    @Override
    protected void applyTransformation(float interpolatedTime, Transformation t) {
        LayoutParams params = view1.getLayoutParams();
        params.leftMargin = (int)(50 * interpolatedTime);
        view1.setLayoutParams(params);
    }
};
animation.setDuration(300);
animation.setInterpolator(new OvershootInterpolator());
view1.startAnimation(animation);

Or better still, use a helper library:

ViewPropertyObjectAnimator.animate(view1).leftMargin(50).setDuration(300).start();

Upvotes: 1

user
user

Reputation: 87064

You could use a ValueAnimator like this:

ValueAnimator varl = ValueAnimator.ofInt(50);
varl.setDuration(4000);
varl.addUpdateListener(new AnimatorUpdateListener() {

    @Override
    public void onAnimationUpdate(ValueAnimator animation) {
        RelativeLayout.LayoutParams lp = (RelativeLayout.LayoutParams) view1.getLayoutParams();
        lp.setMargins((Integer) animation.getAnimatedValue(), 0, 0, 0);
        view1.setLayoutParams(lp);      
    }
});
varl.start();

The ValueAnimator is available from Honeycomb but you have the NineOldAndroids port.

Upvotes: 5

Related Questions