5. 進階UI控制元件-Adapter使用
• ArrayAdapter用途
• 作用為陣列與ListView之間的橋梁
• 可將陣列中定義的資料逐一的對應到ListView之中顯示
• 一般ArrayAdapter中顯示的ListView每行通常只有一個TextView
ArrayList ListView
Jarey
Jarey
TextView-Two
John
John
ArrayAdapter
May TextView-Two
Ken May
TextView-Two
Ken
TextView-Two
為你把關每一道 學習品質 229
6. 進階UI控制元件-Adapter使用
• SimpleAdapter用途
• simpleAdapter可以定製每一列ListView中要顯示的內容
• 一般ListView中每一列的版面配置(Layout)會撰寫在XML檔中,在
由SimpleAdapter負責將內容(Data)填入Layout中的元件(View)。
ArrayList ListView
HashMap Jarey
09222222
Name Jarey
John
Phone 0922 SimpleAdapter
09333333
HashMap May
09444444
Name John
Phone 0933 Ken
095555555
為你把關每一道 學習品質 230
10. 進階UI控制元件-ListView
• ListView使用方式
• set data source to Adapter
• get ListView from R.layout
• set adapter to ListView
• set click listener for each list item
• ListView Event處理函式
• onItemClick(AdapterView<?> parent, View view, int position, long id)
• onItemLongClick(AdapterView<?> parent, View view, int position, long id)
• onItemSelected(AdapterView<?> parent, View view, int position, long id)
為你把關每一道 學習品質 234
13. 進階UI控制元件-ListView
• ListActivity使用方式
• Application extended ListActivity
• set data source to Adapter
• get ListView from ListActivity
• set adapter to ListView
• set click listener for each list item
• ListView Event處理函式
• 在ListActivity中不用註冊Listener,而是直接以覆寫
(Override)來進行事件處理
• 可處理的Event函式與ListView相同
為你把關每一道 學習品質 237
114. SQLite DataBase-SQLiteOpenHelper
• 如何建立SQLiteOpenHelper類別
private static final String DATABASE_NAME = "dbForTest.db";
private static final int DATABASE_VERSION = 1;
private static final String TABLE_NAME = "diary";
private static final String TITLE = "title";
private static final String BODY = "body";
private static class DatabaseHelper extends SQLiteOpenHelper {
DatabaseHelper(Context context) {
super(context, DATABASE_NAME, null, DATABASE_VERSION);
}
@Override
public void onCreate(SQLiteDatabase db) {
String sql = "CREATE TABLE " + TABLE_NAME + " (" + TITLE
+ " text not null, " + BODY + " text not null " + ");";
db.execSQL(sql);
}
@Override
public void onUpgrade(SQLiteDatabase db, int oldVersion, int newVersion) {
}
}
為你把關每一道 學習品質 338
115. SQLite DataBase-SQLiteOpenHelper
• 取得透過SQLiteOpenHelper取得SQLiteDatabase類別
Public Methods
synchronized SQLiteDatabase getReadableDatabase()Create and/or open a database.
synchronized SQLiteDatabase getWritableDatabase()Create and/or open a database
that will be used for reading and writing.
• 利用SQLiteDatabase提供的函式可以存取操作資料庫
• public Cursor rawQuery (String sql, String[] selectionArgs)
• 最低階的操作函式,可以直接接受標準SQL語法
• 為方便不熟SQL語法的開發者,另外有提供一系列的API函式,系統
會將API指令自動轉換成標準的SQL語法呼叫資料庫。
• pubilc delete(….)
• pubilc insert(….)
• pubilc update(….)
• public Cursor query (….)
為你把關每一道 學習品質 339
143. ContentProvider元件-自建ContentProvider
• Diary類別實作
public final class Diary {
//這裡的 AUTHORITY 要求是唯一,而且和Manifest當中provider標籤的AUTHORITY內容一致
public static final String AUTHORITY = "com.ex09_2_contentprovider.diarycontentprovider";
private Diary() {}
public static final class DiaryColumns implements BaseColumns {
// This class cannot be instantiated
private DiaryColumns() {}
public static final Uri CONTENT_URI = Uri.parse("content://" + AUTHORITY + "/diaries");
public static final String CONTENT_TYPE = "vnd.android.cursor.dir/vnd.google.diary";
public static final String CONTENT_ITEM_TYPE =
"vnd.android.cursor.item/vnd.google.diary";
public static final String DEFAULT_SORT_ORDER = "created DESC";
public static final String TITLE = "title";
public static final String BODY = "body"; _id title body create
public static final String CREATED = "created";
unique-id 標題 內文 建立時間
}
} unique-id 標題 內文 建立時間
為你把關每一道 學習品質 367
154. Android Thread運作機制-Looper與MQ
• Handler建構與Callback方式(框架原始碼)
public Handler(Looper looper, Callback callback) {
mLooper = looper;
mQueue = looper.mQueue;
mCallback = callback;
}
public interface Callback {
public boolean handleMessage(Message msg);
}
public void dispatchMessage(Message msg) {
if (msg.callback != null) {
handleCallback(msg);
} else {
if (mCallback != null) {
if (mCallback.handleMessage(msg)) {
return;
}
}
handleMessage(msg);
}}
為你把關每一道 學習品質 378 378
155. Android Thread運作機制-Looper與MQ
• 透過obtainMessage可取得Message物件
• public final Message obtainMessage (int what, int arg1, int
arg2, Object obj)
• 取得Message與傳送Message至MQ中
Handler h = new Handler(){
public void handleMessage(Message msg){
//處理message
}
}
h.removeMessage(0);
h.obtainMessage(1,1,1,”my message);
h.sendMessage(m);
為你把關每一道 學習品質 379 379
156. Android Thread運作機制-Looper與MQ
public static final void prepare() {
• 替子執行緒產生Looper與MQ if (sThreadLocal.get() != null) {
throw new RuntimeException(
Class subThread implements Runnable{ "Only one Looper may be created
public void run(){ per thread");
}
Looper.prepare(); 框架原始碼
sThreadLocal.set(new Looper());
}
h = new Handler(){
public handlerMessage(Message msg){
//處理message
}
};
private Looper() {
Looper.loop(); 框架原始碼 mQueue = new MessageQueue();
mRun = true;
} mThread = Thread.currentThread();
} }
為你把關每一道 學習品質 380 380
166. 如何變更UI Thread內容-使用asyncTask類別
public void onClick(View v) {
new DownloadFilesTask().execute(url1, url2, url3)
}
private class DownloadFilesTask extends AsyncTask<URL, Integer, Long> {
protected Long doInBackground(URL... urls) {
int count = urls.length;
long totalSize = 0;
for (int i = 0; i < count; i++) {
totalSize += Downloader.downloadFile(urls[i]);
publishProgress((int) ((i / (float) count) * 100));
}
return totalSize;
}
protected void onProgressUpdate(Integer... progress) {
setProgressPercent(progress[0]);
}
protected void onPostExecute(Long result) {
showDialog("Downloaded " + result + " bytes");
}
}
為你把關每一道 學習品質 390 390
167. 正確的Thread使用觀念
• AsyncTask 於API中提到的四個注意事項
• The task instance must be created on the UI thread.
• execute(Params…) must be invoked on the UI thread.
• Do not call onPreExecute(),onPostExecute(Result),
doInBackground(Params…), onProgressUpdate(Progress…)
manually.
• The task can be executed only once (an exception will be thrown
if a second execution is attempted.)
• Thread並非萬靈丹
• Thread並不能取代Services元件
• 在背景的Activity隨時都有可能被系統Kill掉,但Thread
可能還在繼續跑。
• Thread適用於短時間,一次性處理函式。
• 一般系統層級,需要長時間服務,與穩定性的,請使用
Services元件來 (IntentServices)
為你把關每一道 學習品質 391 391
215. 多媒體元件-MediaPlayer元件
• MediaPlayer的建構方式
• 利用靜態create函式建構
public static MediaPlayer create (Context context, Uri uri)
public static MediaPlayer create (Context context, int resid)
public static MediaPlayer create (Context context, Uri uri, SurfaceHolder holder)
• 透過new建構
MediaPlayer mediaPlayer = new MediaPlayer();
public void setDataSource (String path)
public void setDataSource (FileDescriptor fd, long offset, long length)
public void setDataSource (FileDescriptor fd)
public void setDataSource (Context context, Uri uri)
為你把關每一道 學習品質 439 439
259. Android的UI設計模式
• Dashboard
• A quick intro to an app, revealing capabilities and
proactively highlighting new content
• Full-screen
• Can be organized by:
• Features
• Categories
• Accounts
• Recommendations
• DO highlight what’s new
• DO focus on 3-6 most important choices
• DO be flavorful
483 483
260. Android的UI設計模式
• Action Bar
• Dedicated real estate at top of the screen to support navigation and
frequently used operations
• Replaces title bar
• Best for actions common across your app
• Search
• Refresh
• Compose (new)
• Can provide a quick link back to dashboard
(or other app home)
• Recommendations
• DO use to bring key actions onscreen
• DO help to convey a sense of place
• DO use consistently within your app
• DON’T use for contextual actions
484
261. Android的UI設計模式
• Quick Actions
• Action popup triggered from distinct visual target
• Minimally disruptive to screen context
• Actions are straightforward
• Fast & fun
• Recommendations
• DO use when items have competing internal
targets
• DO present only the for most important and
obvious actions
• DO use when the item doesn’t have a meaningful
detail view
• DON’T use in contexts which support multiple
selection
485 485
262. Android的UI設計模式
• Search Bar
• Consistent pop-in search form anchored to top of
screen
• Replaces action bar (if present)
• Support suggestions
• Can use corpora selector to alter search mode
Alternately, can offer suggestions for primary
search mode,and additional items for triggering
other modes
• Recommendations
• DO use for simple searches
• DO present rich suggestions
• DO use the same behavior
486
263. Android的UI設計模式
• Companion Widget
• Supports the app by displaying its content and capabilities on the
Home screen
• Makes Home feel more custom, personalized
• Recommendations
• DO provide value above a simple app icon (content)
• DON’TDO handoff to the full app for real tasks
• DO be space efficient
• just provide a larger app launcher
487 487