- Make new android project named as you want to.
- Create a new folder named anim in res directory and then create new xml file named shakeimage under anim folder.
- Put an image (jpg or png) in drawable-mdpi folder.
- Below are codes for shakeimage xml, activity_main layout xml and MainActivity :
activity_main.xml<?xml version="1.0" encoding="utf-8"?> <set xmlns:android="http://schemas.android.com/apk/res/android"> <rotate android:fromDegrees="-60" android:toDegrees="60" android:pivotX="50%" android:pivotY="50%" android:duration="200" android:repeatMode="reverse" android:repeatCount="infinite" android:interpolator="@android:anim/cycle_interpolator"/> </set>
MainActivity.java<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android" android:layout_width="match_parent" android:layout_height="match_parent" > <ImageView android:id="@+id/shakeimg" android:layout_width="wrap_content" android:layout_height="wrap_content" android:layout_centerInParent="true" /> </RelativeLayout>
You can play with rotate attribute below to get more exciting result.package com.example.shakeimage; import android.os.Bundle; import android.app.Activity; import android.view.View; import android.view.animation.Animation; import android.view.animation.AnimationUtils; import android.widget.ImageView; public class MainActivity extends Activity { ImageView shakeimg; Animation animshake; // animation int counttap; // tap counter @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.activity_main); //load animation animshake = AnimationUtils.loadAnimation(this ,R.anim.shakeimage); shakeimg = (ImageView) findViewById(R.id.shakeimg); shakeimg.setImageResource(R.drawable.iconm481); //implement OnClickListener to ImageView shakeimg.setOnClickListener(new View.OnClickListener() { @Override public void onClick(View v) { counttap+=1; // count tap //start animation at first tap if(counttap==1){shakeimg.startAnimation(animshake);} //stop animation at second tap else if(counttap==2){shakeimg.setAnimation(null); counttap=0;} } }); } }
android:fromDegrees : start degree.
android:toDegrees : end degree.
android:pivotX : X center.
android:pivotY ; y center.
android:duration : rotation time
android:repeatMode : restart for rotate continuosly, reverse for back-fro.
android:repeatCount : how many time to repeat.
android:interpolator : animation rate of change.
Result:



Awesome.. simple and to the point.. Thank you.
ReplyDeleteIt's working nice. Thank you...
ReplyDelete