Reputation: 19
I am trying to get frame by frame animation but its giving me a force close and I am not sure as to why it is giving me a force close. It all seems alright to me.
Here is my code i hope some one can help? Thanks in advance.
AnimationTest.java
import android.app.Activity;
import android.graphics.drawable.AnimationDrawable;
import android.graphics.drawable.BitmapDrawable;
import android.os.Bundle;
import android.widget.ImageView;
public class AnimationTest extends Activity {
AnimationDrawable animation;
/** Called when the activity is first created. */
@Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
AnimationDrawable animation = new AnimationDrawable();
animation.addFrame(getResources().getDrawable(R.drawable.up), 500);
animation.addFrame(getResources().getDrawable(R.drawable.down), 500);
animation.setOneShot(false);
ImageView imageAnim = (ImageView) findViewById(R.id.imageView1);
imageAnim.setBackgroundDrawable(animation);
// start the animation!
animation.start();
}
}
activity_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">
<ImageView android:id="@+id/imageView1"
android:src="@drawable/down"
android:layout_height="wrap_content"
android:layout_width="wrap_content"/>
</LinearLayout>
Upvotes: 1
Views: 1986
Reputation: 9296
You're starting the animation in the onCreate Method , which will not work because your activity is not displaying yet, use a delayed runnable instead or a clickListener.
you can test the animation using this code:
// inside onCreate
setContentView(R.layout.activity_main);
final AnimationDrawable animation = new AnimationDrawable();
animation.addFrame(getResources().getDrawable(R.drawable.up), 500);
animation.addFrame(getResources().getDrawable(R.drawable.down), 500);
animation.setOneShot(false);
ImageView imageAnim = (ImageView) findViewById(R.id.imageView1);
imageAnim.setBackgroundDrawable(animation);
Handler handler = new Handler();
handler.postDelayed(new Runnable(){
public void run(){
animation.start();
}
}, 3000);
Please make sure your ImageView has size, and no src is set to see what is going on, in your layout xml file do the following:
android:layout_width="50dp"
android:layout_height="50dp"
and remove src attribute if any
Upvotes: 1
Reputation: 10518
You cant start animation from onCreate method. There is no view yet and activity is not visible. Read this and change you code a little and it will work. I hope so )
Upvotes: 1