Common 目標
- 本篇主要教學如何撰寫跳轉的java檔,
如何從歡迎畫面(WelcomeActivity)跳轉到主畫面(MainActivity)
- 歡迎畫面則是自行發揮
實現方式
步驟1:歡迎畫面的java檔
- 撰寫一個Activity時,通常有前端Layout的xml檔,也有處理後端資料的java檔
- 找到歡迎畫面對應的java檔,進行撰寫
步驟2:onCreate
- 每個Activity必備的code
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_welcome);
}
步驟3:跳轉畫面
方法1:Thread.sleep(long millis)
new Thread(new Runnable() {
@Override
public void run() {
try{
Thread.sleep(2000);
startActivity(new Intent().setClass(WelcomeActivity.this,MainActivity.class));
}catch (InterruptedException e){
e.printStackTrace();
}
}
}).start();
方法2:postDelayed(Runnable r, long delayMillis)
- import android.os.Handler;
new Handler().postDelayed(new Runnable() {
@Override
public void run() {
startActivity(new Intent(WelcomeActivity.this, MainActivity.class));
finish();
}
}, 2000);
方法3:sendEmptyMessageDelayed(int what, long delayMillis)
- int what 表接收者識別接收到的訊息
- 該方法是送一個空的訊息給Handler,所以不用把東西特別包成Message型態,可以直接送一個int的值。
- 這個int的值可以是任何的int數值,但慣例都會填 0
- 個人覺得方法3非常多此一舉,不如使用方法2
@Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.welcome_layout);
mHandler.sendEmptyMessageDelayed(GOTO_MAIN_ACTIVITY, 2000);
}
private static final int GOTO_MAIN_ACTIVITY = 0;
private Handler mHandler = new Handler() {
public void handleMessage(android.os.Message msg) {
switch (msg.what) {
case GOTO_MAIN_ACTIVITY:
Intent intent = new Intent();
intent.setClass(WelcomeActivity.this, MainActivity.class);
startActivity(intent);
finish();
break;
default:
break;
}
}
};
步驟4:修改 AndroidManifest.xml
- 將啟動畫面,從主畫面MainActivity,改成歡迎畫面WelcomeActivity
<activity android:name=".WelcomeActivity">
<intent-filter>
<action android:name="android.intent.action.MAIN" />
<category android:name="android.intent.category.LAUNCHER" />
</intent-filter>
</activity>
<activity android:name=".MainActivity" />
結果呈現
via GIPHY
Reference 參考資料
- http://cookiesp.pixnet.net/blog/post/97619003-android---歡迎畫面跳轉到主activity
- http://givemepass.blogspot.tw/2013/11/splashscreen.html
- What does zero mean in Handler.sendEmptyMessage(0):
https://stackoverflow.com/questions/15338977/what-does-zero-mean-in-handler-sendemptymessage0
- Handler:https://developer.android.com/reference/android/os/Handler.html
沒有留言:
張貼留言