2013-07-18 120 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); 
    }  
};