1

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

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

当我简单地在“onCreate”方法中使用带有固定 int 的 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");
        }
    }

}
4

2 回答 2

2

不要像使用Thread.sleep()(+ 无限循环) 那样阻塞 UI 线程,而是使用 aHandler来进行翻转:

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);
于 2013-07-18T15:03:14.603 回答
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);
    }    
};
于 2013-07-19T08:48:44.540 回答