ImageView and AnimationDrawable
androidImage.setBackgroundResource(R.drawable.android_animate); statement invokes
ImageView's inherited (from
void setBackgroundResourceMethod(int resID) method, setting the view's background to the resource identified by
R.drawable.android_animate argument identifies an XML file named
android_animate.xml (presented later), which stores information on the animation, and which is stored in
drawable subdirectory. The
setBackgroundResource() call links the
androidImage view to the sequence of images described by
android_animate.xml, which will be drawn on this view. The initial image is drawn as a result of this method call.
ImageView lets an app animate a sequence of drawables by calling
AnimationDrawable methods. Before the app can do this, it must obtain
androidAnimation = (AnimationDrawable) androidImage.getBackground(); assignment statement that follows accomplishes this task by invoking
ImageView's inherited (from
Drawable getBackground() method. This method returns the
AnimationDrawable for the given
ImageView, which is subsequently assigned to the
androidAnimation field. The
AnimationDrawable instance is used to start and stop an animation, a process I'll demonstrate shortly.
onCreate(Bundle) turns its attention to creating the Animate button. It invokes
findByViewId(int) to obtain the button information from
main.xml, then instantiates the
It then employs the
View class's nested
onClickListener interface to create a listener object. This object's
void onClick(View v) method is invoked whenever the user clicks the button. The listener is registered with its
Button object by calling
void setOnClickListener(AdapterView.OnClickListener listener) method.
To stop, then start the animation, Animate's click listener invokes
androidAnimation.stop(); followed by
stop() method is called before
start() to ensure that a subsequent click of the Animate button causes a new animation to begin.
Update and save your application code!
Before we continue, replace the skeletal code in your W2A.java tab with the code from Listing 1. Save the contents of this window by pressing Ctrl+S, or select Save from the File menu.
Exploring and coding main.xml
The app's main activity is associated with an XML-based layout, which is stored in file
main.xml, and which is presented in Listing 2.
Listing 2. main.xml
<?xml version="1.0" encoding="utf-8"?> <LinearLayout xmlns:android="http://schemas.android.com/apk/res/android" android:orientation="vertical" android:layout_width="fill_parent" android:layout_height="fill_parent" android:gravity="center" android:background="#ffffff"> <ImageView android:id="@+id/android" android:layout_width="wrap_content" android:layout_height="wrap_content" android:layout_marginBottom="10dip"/> <Button android:id="@+id/animate" android:layout_width="wrap_content" android:layout_height="wrap_content" android:text="@string/animate"/> </LinearLayout>
Sign up for CIO Asia eNewsletters.