Tuesday, July 7, 2015

How to create a rotation animation using ObjectAnimator in Android

activity_main.xml

<RelativeLayout
    xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:tools="http://schemas.android.com/tools"
    android:id="@+id/rl"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    android:padding="10dp"
    tools:context=".MainActivity"
    android:background="#fffffaeb"
    >
    <Button
        android:id="@+id/btn"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:text="Animate"
        />
    <TextView
        android:id="@+id/tv"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:text="CIRCLE"
        android:background="@drawable/rounded_bg"
        android:gravity="center"
        android:elevation="5dp"
        android:translationZ="5dp"
        android:height="100dp"
        android:width="100dp"
        android:layout_below="@id/btn"
        android:layout_marginTop="25dp"
        />
</RelativeLayout>
res/drawable/rounded_bg.xml

<?xml version="1.0" encoding="utf-8"?>
<selector xmlns:android="http://schemas.android.com/apk/res/android">
    <item>
        <shape android:shape="oval">
            <solid android:color="#ffff0008"/>
            <size android:height="10dp" android:width="10dp"/>
            <stroke
                android:color="#ffcd0317"
                android:width="3dp"
                android:dashGap="15dp"
                android:dashWidth="25dp"
                />
        </shape>
    </item>
</selector>
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) {
                ObjectAnimator anim = ObjectAnimator.ofFloat(tv,"rotation",270);
                anim.setDuration(3000);
                anim.start();
            }
        });
   }
}
More android examples