Ahmed Khalaf
Ahmed Khalaf

Reputation: 1419

Programmatically create ImageView in Android

I followed this to create a simple animation.

The example creates manually an ImageView in the main layout, having a resource like this android:src="@anim/anim_android

The problem is, when I make a dynamic ImageView, and I set the resource like this myImageView.setImageResource(R.anim.anim_android);, the animation doesn't work, just views the first image of the sequence.

Any help?

Thanks.

Upvotes: 2

Views: 9206

Answers (1)

Houcine
Houcine

Reputation: 24181

you sould start the animation from you imageView :

myImageView.setImageResource(R.anim.anim_android);
final AnimationDrawable myAnimationDrawable = (AnimationDrawable)myImageViewn.getDrawable();

myImageView.post(
new Runnable(){

  @Override
  public void run() {
   myAnimationDrawable.start();
  }
});
}

EDIT : i think you didn't add the ImageView to your Layout ( contentView of your Activity ) ; try this :

public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);

        RelativeLayout rootLayout = new RelativeLayout(this);
        RelativeLayout.LayoutParams params = new RelativeLayout.LayoutParams(LayoutParams.MATCH_PARENT, LayoutParams.MATCH_PARENT);
        rootLayout.setLayoutParams(params);

        ImageView myAnimation = new ImageView(this);
        RelativeLayout.LayoutParams paramsImage = new RelativeLayout.LayoutParams(LayoutParams.WRAP_CONTENT, LayoutParams.WRAP_CONTENT);
        paramsImage.addRule(RelativeLayout.CENTER_IN_PARENT);
        myAnimation.setLayoutParams(paramsImage);
        myAnimation.setImageDrawable(getResources().getDrawable(R.anim.anim_android));
        rootLayout.addView(myAnimation);

        setContentView(rootLayout);


        final AnimationDrawable myAnimationDrawable = (AnimationDrawable)myAnimation.getDrawable();

        myAnimation.post(new Runnable() {

            @Override
            public void run() {
                myAnimationDrawable.start();
            }
        });
    }

Upvotes: 6

Related Questions