活動檔案夾是SDK1.5引入的,支援開發人員在裝置的案頭上公開ContentProvider,如連絡人、媒體資料等。Android中的活動檔案夾對ContentProvider的作用就相當於RSS閱讀器對發布網站的作用。
活動檔案夾的工作原理如下:
(1)首先在首頁上建立一個表徵圖,表示來自ContentProvider的一組行。通過為表徵圖指定一個URI來進行連結。
(2)當使用者單擊該表徵圖時,系統接受URI並用它掉用ContentProvider。ContentProvider通過遊標返回一組行。
(3)只要此遊標包含活動檔案夾想要的列(比如名稱、描述和單擊時調用的程式)系統就會以ListView或GridView形式呈現這些行。
(4)因為在基礎儲存資料更改時,ListView或GridView能夠更新自己的資料,所以這些視圖被視為活的,活動檔案夾因此而得名。
瞭解了活動檔案夾概念後,接下來介紹如何構建活動檔案夾。要構建活動檔案夾需要兩個東西:一個活動和一個專門的ContentProvider。Android使用次活動標籤來填充可用活動資料夾清單。下面的例子中我們將使用Android內建的ContentProvider:Contacts連絡人,來實現一個連絡人的活動檔案夾。
首先來看描述檔案:AndroidManifest.xml
[java]
<?xml version="1.0" encoding="utf-8"?>
<manifest xmlns:android="http://schemas.android.com/apk/res/android"
package="com.test.livefolder"
android:versionCode="1"
android:versionName="1.0">
<application android:icon="@drawable/icon" android:label="@string/app_name">
<activity android:name=".MainActivity"
android:label="@string/app_name">
<intent-filter>
<strong><category android:name="android.intent.category.DEFAULT" />
<action android:name="android.intent.action.CREATE_LIVE_FOLDER"/></strong>
</intent-filter>
</activity>
</application>
</manifest>
接下來是主活動類:
[java]
public class MainActivity extends Activity {
/** Called when the activity is first created. */
@Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
final Intent intent = getIntent();
final String action = intent.getAction();
//從連絡人取得資料
final Uri uri = Uri.parse("content://contacts/live_folders/people");
if (LiveFolders.ACTION_CREATE_LIVE_FOLDER.equals(action)){
setResult(RESULT_OK, createLiveFolder(uri,"Contacts LF",R.drawable.icon));
}
else{
setResult(RESULT_CANCELED);
}
this.finish();
}
//建立活動檔案夾
private Intent createLiveFolder(Uri uri,String name,int icon){
final Intent intent = new Intent();
//設定Intent
intent.setData(uri);
//活動檔案夾名稱
intent.putExtra(LiveFolders.EXTRA_LIVE_FOLDER_NAME, name);
//活動檔案夾表徵圖
intent.putExtra(LiveFolders.EXTRA_LIVE_FOLDER_ICON, Intent.ShortcutIconResource.fromContext(this, icon));
//顯示模式:列表
intent.putExtra(LiveFolders.EXTRA_LIVE_FOLDER_DISPLAY_MODE, LiveFolders.DISPLAY_MODE_LIST);
return intent;
}
}
運行程式,長按案頭,選擇檔案夾,結果:
然後選擇,Contact live folder在案頭出現一個活動檔案夾,
單擊此活動檔案夾,由於此時沒有連絡人記錄所以活動檔案夾中列表為空白,
我們手動添加2個連絡人記錄後,在點擊Contact LF活動檔案夾,結果
可見活動檔案夾中的資料確實會即時更新。
摘自 fwwdn的專欄