ViewFlipper:使用随机子项以随机时间间隔翻转

时间:2013-07-18 14:24:43

标签: java android viewflipper

我想创建一个菜单,以随机顺序在viewflipper的5个子节点之间以随机时间间隔“翻转”。

我尝试了以下代码,我可以让System.out.println显示我的调试消息,以随机的时间间隔记录在logcat中,这样才能正常工作。 但是,我在模拟器中的屏幕全黑。

当我只使用带有固定int的“onCreate”方法中的setDisplayedChild方法时,它可以正常工作。你能帮帮我吗?谢谢很多!

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");
        }
    }

}

2 个答案:

答案 0 :(得分:1)

不要像使用Thread.sleep()(+无限循环)一样阻止UI线程,而是使用Handler来制作翻转:

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);

答案 1 :(得分:1)

这是我的最终代码。我改变了一些事情:我将randomTime int放在run方法中,以便在每次运行时更新它,因此处理程序会随机延迟。否则,它将根据随机生成的数字的第一次运行而延迟,并且时间间隔将保持不变。我还必须操纵生成的randomTime int,因为如果随机生成的int为0,那么延迟也是0,并且翻转立即发生,这不是我想要的。

万分感谢您的帮助! : - )

private ViewFlipper fliptest;
private Handler testHandler = new Handler();
private Random mRand = new Random();
private Random timerMenu = new Random();
int randomTime;


@Override
protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.activity);


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

private Runnable mFlip = new Runnable() {

    @Override
    public void run() {
        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);
    }    
};