編輯:Android 開發實例
啟動畫面在應用程式中相當常見,通常會伴隨一個背景執行緒,為主程式的啟動預先準備資源。Android 上實作起來並不複雜,以下是最基礎的做法。
建立 splash.xml,內容基本上就是一張鋪滿畫面的 ImageView:
<LinearLayout xmlns:android="https://schemas.android.com/apk/res/android" android:layout_height="fill_parent" android:layout_width="fill_parent" android:orientation="vertical"> <ImageView android:layout_height="fill_parent" android:layout_width="fill_parent" android:scaleType="fitCenter" android:src="@drawable/splash"></ImageView> </LinearLayout>
/** Called when the activity is first created. */
@Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.splash);
Handler x = new Handler();
x.postDelayed(new splashhandler(), 2000);
}
class splashhandler implements Runnable{
public void run() {
startActivity(new Intent(getApplication(),MainActivity.class));
SplashActivity.this.finish();
}
}
關鍵是 postDelayed():延遲兩秒後跳轉到 MainActivity,並立刻 finish 掉 SplashActivity,避免使用者按返回鍵又回到啟動畫面。
上面這個範例用固定秒數硬跳,缺點很明顯:如果初始化還沒做完就跳頁,使用者會看到空白畫面;如果早就準備好了,又會白等兩秒。比較穩健的做法有兩個方向:
windowBackground 設定啟動圖,不必額外開一個 Activity,也不會有版面配置的膨脹成本。另外提醒:真正耗時的初始化工作應該放在背景執行緒,不要在 onCreate() 或主執行緒裡做 I/O。
Android 讀取網路 JSON:從字串到可用物件的三個步驟
行動裝置上的資料多半來自網路,而網路上的資料多半是 JSON。JSON 的全名是 JavaScript Object Notation,是一種不依附任何平台的純文字資料格
Android 檔案選擇器實作教學
檔案選擇器的用途 Android 檔案選擇器常用於讓使用者瀏覽 SD 卡或內部儲存空間,並選取特定檔案。它的概念類似傳統桌面平台的 OpenFileDialog,重點在於
Android JSON 剖析教學:JSONObject 與天氣資料
在 Android 開發中,JSON 解析是取得遠端資料的關鍵步驟。相較於 XML,JSON 更精簡,也更容易與 Web API 搭配。 先找出需要的欄位 解析前,先確認
Android 天氣 App 教學:JSON 資料到底怎麼讀
做過網路相關的 App 就會知道,伺服器回傳的資料幾乎都是 JSON。它是 JavaScript Object Notation 的縮寫,憑藉著結構清晰、沒有冗餘標籤這兩