活動文件夾的工作原理如下:
(1)首先在主頁上創建一個圖標,表示來自ContentProvider的一組行。通過爲圖標指定一個URI來進行鏈接。
(2)當用戶單擊該圖標時,系統接受URI並用它掉用ContentProvider。ContentProvider通過遊標返回一組行。
(3)只要此遊標包含活動文件夾想要的列(比如名稱、描述和單擊時調用的程序)系統就會以ListView或GridView形式呈現這些行。
(4)因爲在基礎存儲數據更改時,ListView或GridView能夠更新自己的數據,所以這些視圖被視爲活的,活動文件夾因此而得名。
瞭解了活動文件夾概念後,接下來介紹如何構建活動文件夾。要構建活動文件夾需要兩個東西:一個活動和一個專門的ContentProvider。Android使用次活動標籤來填充可用活動文件夾列表。下面的例子中我們將使用Android內置的ContentProvider:Contacts聯繫人,來實現一個聯繫人的活動文件夾。
首先來看描述文件:AndroidManifest.xml
<?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>
<category android:name="android.intent.category.DEFAULT" />
<action android:name="android.intent.action.CREATE_LIVE_FOLDER"/>
</intent-filter>
</activity>
</application>
</manifest>
接下來是主活動類:
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活動文件夾,結果如圖: