Want to animate your activity from right to left when you click the home icon in the top left corner of your app?

Simples:


public static void goHomeTop(Activity context) {

final Intent intent = new Intent(context, HomeActivity.class);

intent.setFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP);

context.startActivity(intent);

context.overridePendingTransition(android.R.anim.slide_in_left, android.R.anim.slide_out_right);

}

Maybe you’d like to perform a nice subtle animation such as fading some text in as soon as your activity launches? If you try to start this animation in onCreate() or onResume() you’ll be sorely dissapointed.

One possible solution is to set a timer in one of these methods so that the animation will spawn after a fixed interval.  This approach is problematic because if the delay is too short the animation won’t start (as before) and if it’s too long then the user experience will drop. Furthermore, such a delay might not behave quite the same on a G1 compared to a spanking new Samsung Galaxy S II for example.

A better way is to start the animation in the onWindowFocussedChanged method which is called when the current window of the activity gains or loses focus and gives the best indicator whether the activity is visible to the user. You can use the *hasFocus* parameter to distinguish between gaining or losing focus. Example below:

   private TextView myTextView;

   /** Called when the activity is first created. */
   @Override
   public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_home);

        myTextView= (TextView)findViewById(R.id.my_textview);

        anim = AnimationUtils.loadAnimation(this, R.anim.fade_in);
    }

   @Override
   public void onWindowFocusChanged (boolean hasFocus) {
      super.onWindowFocusChanged(hasFocus);
      if (hasFocus)
         myTextView.startAnimation(anim);
   }

The animation itself is defined in an xml file in res/anim/fade_in.xml:

<?xml version="1.0" encoding="utf-8"?>
<alpha xmlns:android="http://schemas.android.com/apk/res/android"
       android:interpolator="@android:anim/accelerate_interpolator"
       android:fromAlpha="0.0" android:toAlpha="1.0"
       android:duration="1500" />