2013-06-18 45 views
0

後不顯示我有三個佈局:佈局等待

Layout1 
-->onClick()-->show 
Layout2 
-->wait three seconds-->show 
Layout3 

的問題是,佈局2不顯示。要設置我用

setContentView(int); 

佈局相關的代碼可能是:

public class TrainingActivity extends Activity { 

    @Override 
    protected void onCreate(Bundle savedInstanceState) { 
     super.onCreate(savedInstanceState); 
     setContentView(R.layout.layout1); 
     final Button inputButton = (Button)findViewById(R.id.inputButton); 
     inputButton.setOnClickListener(new OnClickListener() { 
      @Override 
      public void onClick(View v) { 
        changeLayouts(); 
      } 
     }); 
    } 
    public void changeLayouts() { 
     setContentView(R.layout.layout2); 
     try { 
      TimeUnit.MILLISECONDS.sleep(3000); 
     } catch (InterruptedException e) { 
      e.printStackTrace(); 
     } 
     setContentView(R.layout.layout3); 
    } 
} 

我的想法是,Android人物可能會使用類似的「事件循環」(如QT)和我的方法將阻塞控制返回到「事件循環」,這將使佈局顯示。 但我找不到我的錯誤。

+2

重新考慮你的設計。爲什麼在第一個地方爲同一個活動多次使用setContentView? – Raghunandan

+0

我不知道爲什麼這個具體失敗,我很驚訝它沒有引發NotResponding。如果您希望在暫停三秒後觸發UI操作,請考慮使用[AsyncTask](http://developer.android.com/reference/android/os/AsyncTask.html)。 – DevOfZot

回答

1

爲什麼你的layout2沒有顯示的問題是因爲TimeUnit.MILLISECONDS.sleep(3000); - 你在這裏做的是你把你的UI線程進入睡眠狀態,所以UI線程無法處理你的請求來改變佈局。當它醒來 - 它立即設置layout3這就是爲什麼layout2沒有顯示。

你可能會考慮使用Handler.postDelayed(Runnable, long)推遲執行

所以這應該是你的預期:

public class TrainingActivity extends Activity { 

    @Override 
    protected void onCreate(Bundle savedInstanceState) { 
     super.onCreate(savedInstanceState); 
     setContentView(R.layout.layout1); 
     final Button inputButton = (Button)findViewById(R.id.inputButton); 
     inputButton.setOnClickListener(new OnClickListener() { 
      @Override 
      public void onClick(View v) { 
        changeLayouts(); 
      } 
     }); 
    } 
    public void changeLayouts() { 
     setContentView(R.layout.layout2); 
     Handler handler = new Handler(); 
     handler.postDelayed(new Runnable() { 

      @Override 
      public void run() { 
       setContentView(R.layout.layout3); 
      } 
     }, 3000); 

    } 
} 
0

試試這個,它肯定會工作

public void changeLayouts() { 
     setContentView(R.layout.layout2); 

     Thread Timer = new Thread(){ 
     public void run(){ 
      try{ 
       sleep(3000); 
      } catch(InterruptedException e){ 
       e.printStackTrace(); 
      } finally { 
       setContentView(R.layout.layout3);     
      } 
     }  
    }; Timer.start(); 
}