作者热门文章
- html - 出于某种原因,IE8 对我的 Sass 文件中继承的 html5 CSS 不友好?
- JMeter 在响应断言中使用 span 标签的问题
- html - 在 :hover and :active? 上具有不同效果的 CSS 动画
- html - 相对于居中的 html 内容固定的 CSS 重复背景?
我想创建一个菜单,它以随机时间间隔在 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/
我是一名优秀的程序员,十分优秀!