Reputation: 3854
I have an ImageView
and 16 images. I want to change the background image according to these images. I used Handler
but the result is not changing smoothly. How can I make the changing more smooth? Do you think AnimationDrawable
is better? This is my code
private static int[] drawable_img_Array = { R.drawable.img01, R.drawable.img02,R.drawable.img03,R.drawable.img04,
R.drawable.img05, R.drawable.img06,R.drawable.img07,R.drawable.img08,
R.drawable.img09, R.drawable.img10,R.drawable.img11,R.drawable.img12,
R.drawable.img13, R.drawable.img14,R.drawable.img15};
final Handler handler = new Handler();
handler.postDelayed(new Runnable(){
public void run(){
if(i<drawable_img_Array.length) {
imgView.setImageResource(drawable_img_Array[i]);
i++;
} else {
i=0;
}
handler.postDelayed(this, 100);
}
}, 100);
This is my second way using AnimationDrawable
animation = new AnimationDrawable();
for (int j=0;j<drawable_ring_Array.length;j++)
{
animation.addFrame(getResources().getDrawable(drawable_img_Array[j]), 100);
}
animation.setOneShot(false);
ImageView imgView = (imgView) findViewById(R.id.img);
RelativeLayout.LayoutParams params = new RelativeLayout.LayoutParams(400, 400);
params.alignWithParent = true;
params.addRule(RelativeLayout.CENTER_IN_PARENT);
imgView.setLayoutParams(params);
imgView.setImageDrawable(animation);
imgView.post(new Starter());
Upvotes: 0
Views: 1029
Reputation: 2795
There are some logical error in your code. That are as follows :
Firstly Your else portion will not work as expected. it should be like this :
} else {
i=0;
imgView.setImageResource(drawable_img_Array[i]);
i++;
}
Finally that could be the real problem run code on UI thread like that
private static int[] drawable_img_Array = {R.drawable.img01,
R.drawable.img02, R.drawable.img03, R.drawable.img04,
R.drawable.img05, R.drawable.img06, R.drawable.img07, R.drawable.img08,
R.drawable.img09, R.drawable.img10, R.drawable.img11, R.drawable.img12,
R.drawable.img13, R.drawable.img14, R.drawable.img15};
final Handler handler = new Handler();
handler.new Runnable() {
public void run() {
runOnUiThread(new Runnable() {
@Override
public void run() {
if (i < drawable_img_Array.length) {
imgView.setImageResource(drawable_img_Array[i]);
i++;
} else {
i=0;
imgView.setImageResource(drawable_img_Array[i]);
i++;
}
handler.postDelayed(this, 100);
}
});
}
}
, 100);
Hope it whould work if not than post the log/error so we can help.
Upvotes: 2
Reputation: 28229
Use an ImageSwitcher
<ImageSwitcher
android:id="@+id/image_switcher"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:inAnimation="@anim/fade_in_image"
android:outAnimation="@anim/fade_out_image">
</ImageSwitcher>
you can create any animations you want and use them for in/out.
Now when calling imageSwitcher.setImageResource(myNextImage)
it'll animate the transition.
Upvotes: 0