gpt4 book ai didi

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

转载 作者:行者123 更新时间:2023-11-29 21:38:37 27 4
gpt4 key购买 nike

我想创建一个菜单,它以随机时间间隔在 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");
}
}

}

最佳答案

不要像使用 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);

关于java - ViewFlipper:使用随机子项以随机时间间隔翻转,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/17726228/

27 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com