很多程序在完全載入之前往往會先顯示一個載入界面,提示用戶等待,這樣對提高用戶體驗有很大作用。本文就為大家提供一個Android程序載入界面的開發實例。
此實例中程序載入界面的顯示過程是,打開程序,出現載入界面,顯示進度條並在後台進行初始化工作,效果如下圖(5個小圓點會循環變色):
下面介紹該實例主要代碼的編寫過程。
一、創建進行初始化工作的線程:
Java代碼
- class InitialThread extends Thread{
-
- @Override
-
- public void run()
-
- {
-
- try {
- Thread.sleep(time);//替換為初始化代碼....
-
- Message msg;
- msg = new Message();
- msg.what = TYPE_STOP;
-
- myHandler.sendMessage(msg);
- } catch (InterruptedException e) {
- // TODO Auto-generated catch block
-
- e.printStackTrace();
-
- Message msg;
- msg = new Message();
- msg.what = TYPE_STOP;
-
- myHandler.sendMessage(msg);
-
- }
-
- }
- }
二、創建界面更新線程,用來控制小圓點的變色:
Java代碼
- class IndexThread extends Thread
- {
-
- @Override
-
- public void run() {
-
- Message msg;
-
- while(!isStop) {
-
- for(int i= 0 ; i < count ; i++) {
- msg = new Message();
- msg.what = TYPE_SELECTED;
- msg.arg1 = imgIDs;
-
- myHandler.sendMessage(msg);
- msg = new Message();
-
- if(i==0) {
-
- msg.what = TYPE_NO_SELECTED;
- msg.arg1 = imgIDs[count-1];
-
- myHandler.sendMessage(msg);
-
- } else {
-
- msg.what = TYPE_NO_SELECTED;
- msg.arg1 = imgIDs[i-1];
- myHandler.sendMessage(msg);
- }
-
- SystemClock.sleep(500);
-
- }
-
- }
- }
- }
可以看到,IndexThread每隔500ms執行一次for循環,每次循環累計發送5個message到Handler,每個message包含該ImageView的Resource Id和當前狀態(是否被選擇,也就是白色還是綠色),下面一起看看Handler:
Java代碼
- public Handler myHandler = new Handler() {
-
- @Override
-
- public void handleMessage(Message msg) {
-
- switch(msg.what)
-
- {
-
- case TYPE_STOP:
-
- Intent intent = new Intent(LoadingScreen1Activity.this, MainActivity.class);
-
- startActivity(intent);
-
- isStop = true;
-
- finish();
-
- break;
-
- case TYPE_SELECTED:
-
- ((ImageView)findViewById(msg.arg1)).setBackgroundResource(R.drawable.progress_go_small);
-
- break;
-
- case TYPE_NO_SELECTED:
-
- ((ImageView)findViewById(msg.arg1)).setBackgroundResource(R.drawable.progress_bg_small);
-
- break;
-
- }
- }
- };
case TYPE_SELECTED:將對應圓點置成綠色背景
case TYPE_NO_SELECTED:將對應圓點置成白色背景
case TYPE_STOP:表示初始化完成,程序跳轉到主界面
到此,此程序載入界面的實例就基本完成了。大家可以根據自己的喜好修改下程序,實現想要的效果。