Tuesday, July 7, 2015

How to animate alpha property of a View using ObjectAnimator in Android

MainActivity.java

package com.cfsuman.me.androidcodesnippets;

import android.os.Bundle;
import android.app.Activity;
import android.view.View;
import android.widget.Button;
import android.widget.TextView;
import android.animation.ObjectAnimator;

public class MainActivity extends Activity{

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

        Button btn = (Button) findViewById(R.id.btn);
        final TextView tv = (TextView) findViewById(R.id.tv);

        btn.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                // Make the object 50% transparent
                ObjectAnimator anim = ObjectAnimator.ofFloat(tv,"alpha",0.5f);
                anim.setDuration(3000); // duration 3 seconds
                anim.start();
            }
        });
   }
}
More android examples