2015-11-29 68 views
3

我剛開始學習android,對屏幕上的繪圖佈局感到困惑。 我想要做的是,如何在onCreate()方法中顯示MainActivity的佈局?

1>顯示MainActivity的佈局 - 這是在XML佈局文件設計

2>等待2秒,仍表現出MainActivity

3>將上下一個活動

並且用我最近的代碼,它只顯示白色空白屏幕2秒,然後顯示下一個活動。

這是我的MainActivity的源代碼,現在。

public class MainActivity extends AppCompatActivity { 
    Intent settingIntent; 
    @Override 
    protected void onCreate(Bundle savedInstanceState) { 
     super.onCreate(savedInstanceState); 
     setContentView(R.layout.activity_main); 
    } 

    @Override 
    protected void onStart(){ 
     super.onStart(); 
     try { 
      Thread.sleep(2000); 
     } catch(InterruptedException e) { 
      // 
     } 
     settingIntent = new Intent(this,SettingActivity.class); 
     startActivity(settingIntent); 
    } 
} 

我該如何使這項工作成爲我的意圖?

回答

4

你可以使用默認方法View秒 - 之後postDelayd

findViewById(android.R.id.content).postDelayed(new Runnable() { 
     @Override 
     public void run() { 
      Intent settingIntent = new Intent(MainActivity.this, SettingActivity.class); 
      MainActivity.this.startActivity(settingIntent); 
     } 
    }, 2000); 

setContentView(R.layout.activity_main); 

,並刪除調用的OnStart之前onStart

+0

酷炫的方式!現在它運作良好。謝謝你的幫助。 –

0

我知道的是onStart回調說明活動即將顯示。 所以它尚未顯示。更好的選擇是將您的代碼顯示在onResume回調中的新活動。

+0

我也試過這種方式()並沒有奏效。 –

2

當您調用睡眠時,您正在暫停UI線程。這不是你想要的。相反,這樣做:

@Override 
protected void onStart(){ 
    super.onStart(); 
    new Handler(Looper.getMainLooper()).postDelayed(new Runnable() { 
     @Override 
     public void run() { 
      settingIntent = new Intent(MainActivity.this,SettingActivity.class); 
      MainActivity.this.startActivity(settingIntent); 
     } 
    }, 2000); 

} 

編輯

由於Commonsware正確地指出,這有引入內存泄漏的可能性。你應該考慮使用@yidavewu發佈的解決方案。

+1

不要創建'Handler'的匿名內部類實例;你可能會引入內存泄漏。由於'postDelayed()'也是'View'方法,所以使用'findViewById(android.R.id.content).postDelayed(...)'會更安全。 – CommonsWare

+0

@CommonsWare你是對的。我完全忘了View有一個postDelayed方法。 – asadmshah

+0

我不確定sleep()方法是否暫停UI線程,以及如何解決問題。感謝您的詳細解答。 –

相關問題