Search code examples
javaandroidviewflipper

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 to display my debugging message to be logged in the logcat at random time intervals so that's working. However, my screen in the emulator is all black.

When I simply use the setDisplayedChild method in the "onCreate" method with a fixed int, it works fine. Can you help me with this? Thanks many!

public class FlipperTest extends Activity {

int randomTime;
int randomChild;
ViewFlipper fliptest;
@Override
protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.activity_beat_the_game);
    ViewFlipper fliptest = (ViewFlipper) findViewById(R.id.menuFlipper);

            //this would work
            //fliptest.setDisplayedChild(3);

    while (true){
        try {
            Thread.sleep(randomTime);

        } catch (InterruptedException e) {
            e.printStackTrace();
        }finally{
            Random timerMenu = new Random();
            randomTime  = timerMenu.nextInt(6) * 2000;
            Random childMenu = new Random();
            randomChild = childMenu.nextInt(5);
            fliptest.setDisplayedChild(randomChild);

            System.out.println("executes the finally loop");
        }
    }

}

Solution

  • 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;
    private Handler mHandler = new Handler();
    private Random mRand = new Random();
    private Runnable mFlip = new Runnable() {
    
        @Override
        public void run() {
            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);