Skip to content Skip to sidebar Skip to footer

Viewflipper: Flipping At Random Time Intervals Using Random Children

I want to create a menu which 'flips' at random time intervals between 5 children of a viewflipper in random order. I tried the following code and I can get the System.out.println

Solution 1:

Don't block the UI thread like you do with Thread.sleep()(+ infinite loop), instead use a Handler, for example, to make your flips:

private ViewFlipper mFliptest;
privateHandlermHandler=newHandler();
privateRandommRand=newRandom();
privateRunnablemFlip=newRunnable() {

    @Overridepublicvoidrun() {
        mFliptest.setDisplayedChild(mRand.nextInt());
        mHandler.postDelayed(this, mRand.nextInt(6) * 2000);
    }    
}

//in the onCreate method
mFliptest = (ViewFlipper) findViewById(R.id.menuFlipper);
mHandler.postDelayed(mFlip, randomTime);

Solution 2:

Here is my final code. I changed a few things: I put the randomTime int in the run method so that it's updated at each run and therefore the handler gets delayed randomly. Otherwise, it will be delayed according to the first run of the randomly generated number and the time intervals will stay the same. I also had to manipulate the generated randomTime int because if the randomly generated int is 0, then the delay is 0 as well and the flip happens instantly which is not what I wanted.

Thanks a million for your help! :-)

private ViewFlipper fliptest;
privateHandlertestHandler=newHandler();
privateRandommRand=newRandom();
privateRandomtimerMenu=newRandom();
int randomTime;


@OverrideprotectedvoidonCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.activity);


    fliptest = (ViewFlipper) findViewById(R.id.menuFlipper);
    testHandler.postDelayed(mFlip, randomTime);
}

privateRunnablemFlip=newRunnable() {

    @Overridepublicvoidrun() {
        randomTime  = (timerMenu.nextInt(6) + 1) * 2000;

        System.out.println("executes the run method " + randomTime);
        fliptest.setDisplayedChild(mRand.nextInt(6));
        testHandler.postDelayed(this, (mRand.nextInt(6)+ 1) * 2000);
    }    
};

Post a Comment for "Viewflipper: Flipping At Random Time Intervals Using Random Children"