Question

I want my app to switch two images with a delay of, let's say, 3 seconds. This is my former code:

protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.activity_main);

    if (savedInstanceState == null) {
        getFragmentManager().beginTransaction()
                .add(R.id.container, new PlaceholderFragment())
                .commit();
    }

    Handler handler = new Handler();
    handler.postDelayed(new Runnable() {

        @Override
        public void run() {
            ImageView image = (ImageView)      
 findViewById(R.id.imgView_dice0);
            image.setImageResource(R.drawable.dice_6);      
        }
    }, 3000);
}
....

This works for switching the image one time. I tried putting the image-changing in two methods (and replacing R.drawable.dice_6 with R.drawable.dice_1) which are called with a delay, surrounded by a loop. That doesn't work, the app only shows one and the same dice all the time. What should I do?

Was it helpful?

Solution

You should restart your Handler.postDelayed inside the runnable to make it work.

Something like:

final Handler handler = new Handler();
handler.postDelayed(new Runnable() {
    private boolean useDiceOne;

    @Override
    public void run() {
        ImageView image = (ImageView)findViewById(R.id.imgView_dice0);
        if (!useDiceOne) {
         image.setImageResource(R.drawable.dice_6);
        } else {
         image.setImageResource(R.drawable.dice_1);
        }
        useDiceOne = !useDiceOne;
        handler.postDelayed(this, 3000);      
    }
 }, 3000);

useDiceOne will be used to change the image between dice_1 and dice_6 p.s cache the ImageView.

To make it more flexible (stop it when you want, etc.) you could save the handler reference (and runnable reference too) somewhere and use removeCallbacks

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top