2013-07-18 119 views
1

我想创建一个菜单,以随机顺序在视图片快照的5个孩子之间以随机时间间隔“翻转”。ViewFlipper:使用随机孩子随机时间间隔翻转

我试过下面的代码,我可以让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"); 
     } 
    } 

} 

回答

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

感谢许多Luksprog!这非常有帮助!我会在最后的代码下面发帖并解释一下。无论如何,你摇滚! – user2595866

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